gee*_*fun 2 javascript binding coffeescript backbone.js
我试图通过$(this.el)在Backbone模型的成功或错误回调中引用视图元素.
例:
从SomeViewClass(扩展Backbone.View)中,
@model.save({}, {
success: (model, response) ->
($ this.el).removeClass("editing")
})
Run Code Online (Sandbox Code Playgroud)
但是,我坚持认为"this"不引用SomeViewClass实例.有任何想法吗?
由于您使用的是CoffeeScript,因此您可以使用胖箭头(=>
)将当前值绑定this
到您的函数:
@model.save({}, {
success: (model, response) =>
($ this.el).removeClass("editing")
})
Run Code Online (Sandbox Code Playgroud)
如果您使用的是纯JavaScript,那么通常使用标准var self = this;
技巧:
var self = this;
model.save({ }, {
success: function(model, response) {
$(self.el).removeClass("editing");
}
});
Run Code Online (Sandbox Code Playgroud)
或者,因为您正在使用backbone.js(需要underscore.js),您可以使用_.bind
构建绑定函数.
如果您的回调较大或者您想在多个地方使用相同的回调,那么_.bindAll
这将是一个选项.你必须使回调成为一个命名方法; 但是,如果回调很大,你可能想要取消内联它.