将内容保留在Backbone JS视图中

时间:2012-11-05 14:19:45

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

1 个答案:

答案 0 :(得分:3)

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

  

bindAll _.bindAll(object,[* methodNames])
  在methodNames指定的对象上绑定多个方法,以便在   调用该对象的上下文。非常方便   将用作事件处理程序的绑定函数   否则会以相当无用的方式调用。如果不   提供了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/