gpt4 book ai didi

javascript - 在 BackboneJS View 中保持上下文

转载 作者:行者123 更新时间:2023-11-30 13:12:57 27 4
gpt4 key购买 nike

是否有更短更优雅的方式来将上下文保存在 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) {
}
});

http://jsfiddle.net/nikoshr/wAAZ5/

关于javascript - 在 BackboneJS View 中保持上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233979/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com