Dmytro Filipenko
Dmytro Filipenko

Reputation: 941

Incorrect this in backbone binding

 DM.Backbone.View.feedback = Backbone.View.extend( {
     initialize: function (){
        this.render( this.model.get( 'data' ) || [] );
     },
     render: function ( param ){
        if ( $( '.problem_report_reply' ).length > 0 ) {
            _.bind( this.mail_to, this );
            $( '.problem_report_reply' ).off().on( 'click', this.mail_to )
        }
     },
     mail_to: function (){

        console.log( 'this', this )
     } );

Here my code of Backbone.View. I have problem with binding method to DOM element, console.log show this like a DOM element which i clicked. I use undescore method _.bind to correct binding this, what a problem?

Upvotes: 1

Views: 57

Answers (1)

nikoshr
nikoshr

Reputation: 33344

_.bind creates a new function, it doesn't modify an existing one. You could use it like this

render: function ( param ){
    var func;

    if ( $( '.problem_report_reply' ).length > 0 ) {
        func = _.bind(this.mail_to, this);
        $('.problem_report_reply').off().on('click', func);
    }
}

Or use _.bindAll, which does modify the functions in an object

DM.Backbone.View.feedback = Backbone.View.extend({
    initialize: function (){
        _.bindAll(this, "mail_to");
        this.render( this.model.get( 'data' ) || [] );
    },
    render: function ( param ){
        if ( $( '.problem_report_reply' ).length > 0 ) {
            $( '.problem_report_reply' ).off().on('click', this.mail_to)
        }
    },
    mail_to: function (){
        console.log( 'this', this )
    }
});

Upvotes: 2

Related Questions