2

有没有办法自动为一个主干.js 对象做一个 _.bindAll ?

不久前我在和某人交谈,他们说有,但我不知道从哪里开始寻找。

例子:

var TheView = Backbone.View.extend({

    initialize: function() {
        // HOW CAN I AVOID HAVING TO DO THIS?---->
        _.bindAll(this,'render','on_element_01_click', 'on_element_02_click');
    },

    events: {
        'click #element_01': 'on_element_01_click',
        'click #element_02': 'on_element_02_click',
    },

    render: function(){
        return this;
    },

    on_element_01_click: function(){

    },

    on_element_02_click: function(){

    }
}
4

3 回答 3

5

改为这样做:

_.bindAll(this);

将绑定此视图中的所有功能。

于 2012-07-16T21:49:24.510 回答
2

如果你想在你的视图中构建,我已经学会了一种更简单的技术bindAll(这对于像 AJAX 回调方法这样的事情很方便,这些方法不像事件处理程序那样自动绑定)。基本上你只需重写构造函数来执行自动绑定。

var BoundModel = Backbone.Model.extend({
    constructor: function() {
        Backbone.Model.apply(this, arguments);
        if (this.boundMethods) {
            _(this).bindAll.apply(this, this.boundMethods);
        }
    }
})

var SubclassOfBoundModel = Backbone.Model.extend({
     boundMethods: ['handleFetchResponse'],
     initialize: function () {
         this.model.on('sync', this.handleFetchResponse);
     }
     handleFetchResponse: function() {
         // this function is bound to the model instance
     }
})

当然,如果您只想绑定所有方法,则可以省略“boundMethods”部分,只需:

    constructor: function() {
        Backbone.Model.apply(this, arguments);
        _(this).bindAll();
    }
于 2013-01-06T17:57:17.440 回答
1

我自己尝试过这样做,并且能够使用以下方式使其工作:

function bindOnExtend(clazz) {
    var originalExtend = clazz.extend;
    clazz.extend = function() {
        var newSubClass = originalExtend.apply(this, arguments);
        var originalInitialize = newSubClass.prototype.initialize;
        newSubClass.prototype.initialize = function() {
            // The constructor will get broken by bindAll; preserve it so _super keeps working
            var realConstructor = this.constructor;
            _.bindAll(this);
            this.constructor = realConstructor;
            originalInitialize.apply(this, arguments);
        };
        return bindOnExtend(newSubClass);
    };
    return clazz;
}

var BoundModel = Backbone.Model.extend();
bindOnExtend(BoundModel);

var BoundView = Backbone.View.extend();
bindOnExtend(BoundView);

但是,我不会推荐它。这样做将为每个模型/视图/您实例化的任何内容上的每个方法关闭。这不仅会略微增加整体内存使用量,而且如果您不小心,还会增加内存泄漏的可能性。此外,它会使您的堆栈跟踪更长几行,因为它们必须通过 bindOnExtend。

以我的经验,不得不做“ _.bindAll(this, ...”是值得的,因为:

1)它使我的代码对任何追随我的人更清晰/明显 2)它鼓励我限定 my bindAll,而不是仅使用 1-arg 形式 3)我讨厌涉水通过长堆栈跟踪

但是,如果你想要它,上面的代码应该可以工作。

于 2012-07-16T21:55:39.947 回答