如何获取模型内部的组件引用保存回调函数

How to get component reference inside of the model save callback functions?

本文关键字:组件 引用 保存 函数 回调 内部 模型 何获取 获取      更新时间:2023-09-26

我有一个带有模型的登录组件,该组件会转到服务器,如果登录不正确,则会收到错误。

以下是我所说的想法:

var LoginModel = can.Model.extend({
    create : "POST /account/login"
},{});
can.Component.extend({
    tag: "pod-login",
    template: can.view("/static/js/views/login_form.stache"),
    viewModel:{
        login: new LoginModel(),
        processLogin: function(login) {
            // I need to access the component here
        },
        processLoginError: function(response) {
            // I need to access the component here
        }
    },
    events: {
        "#login_button click": function() {
            var form = this.element.find( 'form' );
            var values = can.deparam(form.serialize());
            this.viewModel.login.attr(values).save(
                this.viewModel.processLogin,
                this.viewModel.processLoginError
            );
        }
    }

});

这里的问题是,当我试图在模型登录处理程序中使用"this"时,我得到的对象不是当前组件实例。例如,在项目LogiError上,我得到了xhr引用。

如何访问processLogin和processLoginError中的组件?

我的解决方法是在login_button点击事件中使用$('some_html_element_on_My_template').data('component',this),并在回调函数中访问它,但我认为这可以更好地处理。

有什么见解吗?

您需要将上下文绑定到回调: this.viewModel.login.attr(values).save( this.viewModel.processLogin.bind(this), this.viewModel.processLoginError.bind(this) );

别忘了在IE8中包含es5-shim