我的 Backbone 应用程序中有以下代码,有没有办法将“this”绑定(bind)到回调,而不是一直分配“$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');
}
});
}
最佳答案
您有 Underscore 可用,因此您可以 _.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
});
}
关于jquery - Backbone.js 将其绑定(bind)到成功/错误回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11167698/