javascript - 在 BackboneJS View 中保持上下文

标签 javascript backbone.js

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

相关文章:

javascript - Node.js 不能要求同一目录中的 .js 文件

php - 网页中类似浏览器的功能?

backbone.js - 动态分配backbone.js View el的正确方法

backbone.js - 拉拉维尔。如何在 Backbone 中获取/传递登录用户 ID

javascript - 在 backbone.js 中触发自定义事件

javascript - Google Charts 时间线 - PHP 数组作为输入

javascript - 如果未选中任何单选选项,则发出警报

javascript - 什么是 backbone.js 命名约定?

javascript - 是否可以一次转义多个路由中的所有参数?

javascript - 监听状态和函数调用