Backbone.js将此绑定到成功/错误回调?

Rob*_*Rob 4 jquery bind backbone.js underscore.js

我在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');
        }
   });
}
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 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)
});
Run Code Online (Sandbox Code Playgroud)

或者只是使用回调和/ _.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
    });
}
Run Code Online (Sandbox Code Playgroud)