1

有没有更短更优雅的方式来保持 BackboneJS 视图中的上下文?

    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 将被传递给内部视图事件。

4

1 回答 1

3

您可以使用_.bindAll将其锁定到回调中的视图:

bindAll _.bindAll(object, [*methodNames])
绑定由methodNames 指定的对象上的许多方法,以便在调用它们时在该对象的上下文中运行。对于将用作事件处理程序的绑定函数非常方便,否则将使用相当无用的 this 来调用它们。如果没有提供 methodNames,则对象的所有函数属性都将绑定到它。

你可以像这样使用它

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/

于 2012-11-05T14:34:24.010 回答