Javascript 在BackboneJS视图中保留上下文
是否有一种更简洁、更优雅的方式来保持BackboneJS视图中的上下文Javascript 在BackboneJS视图中保留上下文,javascript,backbone.js,Javascript,Backbone.js,是否有一种更简洁、更优雅的方式来保持BackboneJS视图中的上下文 this.$el.find(this.itemViewContainer).sortable("destroy").sortable({ connectWith:'.tasks', delay:140, revert:200, items:'li:not(.locked)', placeholder:'ui-state-highlight
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)
});
我指的是:
- 开始事件
- 平分
- 停止事件
绑定由MethodName指定的对象上的多个方法,以在 无论何时调用该对象的上下文。非常方便 将用作事件处理程序的绑定函数 否则将以一个相当无用的方式调用。如果没有 如果提供了MethodName,则对象的所有函数属性都将 一定要坚持下去 你可以这样使用它
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) {
}
});
我甚至不用麻烦传递方法名,我只是总是在所有视图的父类中执行
\uu.bindAll(this)
,并将其称为done。视图是面向对象的有状态实例,因此将其函数视为OO方法而不是纯函数是有意义的。当您添加新方法并以这种方式引入bug时,将它们绑定在一起会使您更难意外地忘记其中一个。@PeterLyons-您知道您的方法是否会影响性能吗?是的。这将使您的应用程序速度降低0.0000000000000 321%。@Guy快速性能测试显示性能受到影响,但这仅在您创建数千个视图时才重要,并且您必须将其与Peter列出的收益相平衡。@sam的影响是.bindAll(obj)与.bindAll(obj,“方法”),但由于.bindAll(obj)现在被禁止,这一点毫无意义:)无论如何,请尽可能少地使用u.bindAll方法