javascript - 如何在模型保存回调函数中获取组件引用?

标签 javascript canjs canjs-model

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

这是我正在谈论的想法:

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”时,我得到的对象不是当前组件实例。例如,在 proessLoginError 上我得到了 xhr 引用。

如何访问processLogin和processLoginError内部的组件?

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

有什么见解吗?

最佳答案

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

不要忘记为 IE8 添加 es5-shim

关于javascript - 如何在模型保存回调函数中获取组件引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949754/

相关文章:

javascript - Canjs - 使用附加方法扩展 can.Model

javascript - Canjs 中的验证

JavaScriptMVC:如何使用模型findAll来封装这些URL?

javascript - 显示 :none property not working in firefox and chrome

javascript - 如何在附加了 .bind(this) 的回调中移除 EventListener

javascript - 正则表达式不接受单个字符

javascript - 使用 CanJS 为文档上触发的事件设置全局监听器/ Controller

javascript - canjs 模型上的更多 restfunctions

javascript - 如何从 php 中获取一个值并通过 javascript 将其放入 input-element 中?