我的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');
}
});
}
答案 0 :(得分: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
});
}