主干 - 反正检查事件之前已经被绑定? [英] Backbone - Anyway to check if an event has been bound before?

查看:113
本文介绍了主干 - 反正检查事件之前已经被绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做这里面我的观点之一:

I'm doing this inside one of my Views:

render: function($options) {
    ...

    this.collection.on('reset', _(function() {
        this.render($options);
    }).bind(this));

    ....
}

问题是,每当重置以及重新渲染已被触发,新的重置绑定将被创建,造成2倍,4倍,8倍,等重新渲染的时候,因为它的推移。

The problem is, whenever reset as well as the re-rendering has been triggered, a new reset binding will be created, resulting 2x, 4x, 8x, etc. times of re-rendering as it goes on.

这是一个有点棘手移动结合到初始化部分(这应该可以解决这个问题),但因为它不是一种选择,还有没有其他的解决方案可用,就像骨干检查,如果此事件之前已经绑定,或什么?

It's a bit tricky to move the binding into the initialize section (which should solve this issue), however since it's not an option, is there any other solution available, like having Backbone checking if this event has been bound before, or something?

推荐答案

移动你结合初始化将是最好的,但假设你有充分的理由不,你可以只是设置一个标志:

Moving your binding to initialize would be best but assuming that you have good reasons not to, you could just set a flag:

initialize: function() {
    var _this = this;
    this._finish_initializing = _.once(function($options) {
        _this.collection.on('reset', function() {
            _this.render($options);
        });
    });
    //...
},
render: function($options) {
    this._finish_initializing($options);
    //...
}

有大量的实施标志不同的方式, _。一旦 只是很好地隐藏标志检查。您还可能引发 事件呈现有取消绑定本身就是一个监听器:

There are lots of different ways to implement the flag, _.once just nicely hides the flag checking. You could also trigger an event in render have a listener that unbinds itself:

initialize: function() {
    var finish_initializing = function($options) {
        /* your binding goes here ... */
        this.off('render', finish_initializing);
    };
    this.on('render', finish_initializing, this);
},
render: function($options) {
    this.trigger('render', $options);
    //...
}

这是同样的逻辑真的,只是在不同的衣服打扮。你也可以使用明确标记和如果渲染或一个函数分配给此._finish 初始化键,该功能将删除this._finish

That's the same logic really, just dressed up in different clothes. You could also use an explicit flag and an if in render or assign a function to this._finish in initialize and that function would delete this._finish.

这篇关于主干 - 反正检查事件之前已经被绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆