4

我的 Backbone 应用程序中有以下代码,有没有办法将“this”绑定到回调,而不必一直分配“$this”?

addItem: function()
{
    var $this = this;

    (new Project()).save({name:$('#project_name').val()},{
        success:function(model, response)
        {
            $this.collection.add(model);
        },
        error: function()
        {
            console.log('wtf');
        }
   });
}
4

1 回答 1

9

您有可用的下划线,因此您可以_.bind手动:

(new Project()).save({ name: $('#project_name').val() }, {
    success: _.bind(function(model, response) {
        this.collection.add(model);
    }, this),
    error: _.bind(function() {
        console.log('wtf');
    }, this)
});

或者只是使用回调方法和_.bind/或_.bindAll那些:

initialize: function() {
    _.bindAll(this, 'success_callback', 'error_callback');
},
success_callback: function(model, response) {
    this.collection.add(model);
},
error_callback: function() {
    console.log('WTF?');
},
addItem: function() {
    (new Project()).save({ name: $('#project_name').val() }, {
        success: this.success_callback,
        error:   this.error_callback
    });
}
于 2012-06-23T07:49:25.813 回答