Reputation: 941
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
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