是否有更短更优雅的方式来将上下文保存在 BackboneJS View 中?
this.$el.find(this.itemViewContainer).sortable("destroy").sortable({
connectWith:'.tasks',
delay:140,
revert:200,
items:'li:not(.locked)',
placeholder:'ui-state-highlight',
start:_.bind(function (event, ui){this._sortStart(event, ui);}, this),
receive:_.bind(function (event, ui){this._sortReceive(event, ui);}, this),
stop:_.bind(function (event, ui){this._sortStop(event, ui);}, this)
});
我指的是:
- 开始事件
- 收齐
- 停止事件
重要的是:this、event 和 ui 将传递给内部 View 事件。
最佳答案
您可以使用 _.bindAll将其锁定到回调中的 View :
bindAll _.bindAll(object, [*methodNames])
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this. If no methodNames are provided, all of the object's function properties will be bound to it.
你可以这样使用它
var V = Backbone.View.extend({
initialize: function() {
_.bindAll(this, '_sortStart', '_sortReceive', '_sortStop');
this.$el.sortable("destroy").sortable({
items: 'li:not(.locked)',
start: this._sortStart,
receive: this._sortReceive,
stop:this._sortStop
});
},
_sortStart: function(event, ui) {
},
_sortReceive: function(event, ui) {
},
_sortStop: function(event, ui) {
}
});
关于javascript - 在 BackboneJS View 中保持上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233979/