[英]How to get component reference inside of the model save callback functions?
I have a login component with a model that goes to the server and receives an error if the login was no correct. 我有一个带有模型的登录组件,如果登录不正确,则会转到服务器并收到错误。
Here is the idea of what I'm talking about: 以下是我所说的内容:
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
);
}
}
});
The problem here is that when I try to use "this" inside the model login handlers I'm getting an object that ins't the current component instance. 这里的问题是,当我尝试在模型登录处理程序中使用“this”时,我得到一个不是当前组件实例的对象。 On the proessLoginError I got the xhr reference for instance. 在proessLoginError上我得到了xhr引用。
How to access the component inside processLogin and processLoginError? 如何访问processLogin和processLoginError中的组件?
My workaround here was to use $('some_html_element_on_my_template').data('component', this) inside the login_button click event and access it inside the callback functions but I think that this could be handled better. 我的解决方法是在login_button click事件中使用$('some_html_element_on_my_template')。data('component',this)并在回调函数中访问它,但我认为这可以更好地处理。
Any insight guys? 任何洞察家伙?
You need to bind context to the callbacks: this.viewModel.login.attr(values).save( this.viewModel.processLogin.bind(this), this.viewModel.processLoginError.bind(this) );
您需要将上下文绑定到回调: this.viewModel.login.attr(values).save( this.viewModel.processLogin.bind(this), this.viewModel.processLoginError.bind(this) );
And don't forget to include es5-shim
for IE8. 并且不要忘记为IE8添加es5-shim
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.