1
 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?

4

1 回答 1

2

_.bind创建一个新函数,它不会修改现有函数。你可以像这样使用它

render: function ( param ){
    var func;

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

或者使用_.bindAll,它确实修改了对象中的函数

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 )
    }
});
于 2013-05-24T11:36:04.777 回答