user367956
user367956

Reputation: 35

How to access backbone view in submitHandler callback?

I'm exploring backbone.js and I'm trying to setup simple login page. Here is my view.js file:

window.LoginView = Backbone.View.extend({   

    events: {

    },

    initialize : function() {       
        this.model.bind("error", this.error);       
        this.template = _.template(tpl.get('login'));       
    },  

    login: function(form){
        this.model.set({
            login: $("#login", form).val(),
            password: $("#password", form).val()
        });         
    },  

    render : function(eventName) {      
        $(this.el).html(this.template());   
        $(this.el).find("form").validate({
            submitHandler: this.login
        });
        return this;
    }
});

As you can see I use jquery.validation attached to form in render function. As submitHandler callback I've set login function. This line

this.model.set({...

is giving me this.model is undefined error so I assume that this in login function is not the same as this in initialize or render functions. My question how I can access backbone this in login function?

Upvotes: 1

Views: 351

Answers (1)

Zevan
Zevan

Reputation: 10235

One way is to use jQuery.proxy() to set the value of "this" for the login function:

$(this.el).find("form").validate({
  submitHandler: $.proxy(this.login, this)
});

Proxy returns a new function with a new value for "this". Since "this" in the render function points to your view, you pass it as the second argument to proxy.

Upvotes: 2

Related Questions