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. On the proessLoginError I got the xhr reference for instance.
How to access the component inside processLogin and 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.
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)
);
And don't forget to include es5-shim
for IE8.