简体   繁体   English

处置Collection时,关闭Backbone事件

[英]Turn Backbone events off when Collection is disposed of

I have my Collection subscribing to an event I trigger on the Backbone object itself: 我的Collection订阅了在Backbone对象本身上触发的事件:

const Items = BaseCollection.extend({
    model: ItemModel,

    initialize() {
        BaseCollection.prototype.initialize.apply(this, arguments);
        Backbone.on('api:data:foobar', (data) = > {

        });
    }
});

However, when I create new instances of this Collection, Backbone adds another listener. 但是,当我创建此Collection的新实例时,Backbone添加了另一个侦听器。 When this event is triggered, the callback is fired many many times. 触发此事件后,将触发多次回调。 Is there a way to either: 有没有一种方法可以:

  1. Only set this once per Collection lifecycle? 每个Collection生命周期仅设置一次?
  2. Where is the best place to unsubscribe/turn off this event listener? 退订/关闭此事件侦听器的最佳位置在哪里?

The reason this is happening is because your binding the event handler directly to the Backbone object, every time you create a new instance (which calls the initialize method of your collection). 发生这种情况的原因是,每次创建新实例(调用集合的initialize方法)时,您都将事件处理程序直接绑定到Backbone对象。

What you want to do instead is invert the relationship and have your collection listen to the event and unsubscribe when you are disposing of your collection. 相反,您想要做的是反转关系,让您的收藏集监听事件,并在处理收藏集时退订。 Since version 0.9.9 Backbone provides a built it way to do this using the listenTo . 从0.9.9版开始,Backbone提供了一种内置方法来使用listenTo做到这一点

For example 例如

 initialize() {
        BaseCollection.prototype.initialize.apply(this, arguments);
        this.listenTo(Backbone, 'api:data:foobar', (data) = > {

        });

To unsubscribe/turn off this event listener you can use the the stopListening method (they should also be automatically removed if you remove your collection). 要取消订阅/关闭此事件侦听器,可以使用stopListening方法(如果删除集合,也应将它们自动删除)。 With views when you call remove it will automatically call stopListening . 使用视图时,调用remove时会自动调用stopListening

If you really want to use bind the event handler directly to the Backbone object and bind it just once you could do this in this by moving the event binding outside of your initialize method, but you will probably be better off using listenTo. 如果您真的想直接将事件处理程序绑定到Backbone对象,然后将其绑定一次,则可以通过将事件绑定移到initialize方法之外来实现,但是最好使用listenTo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM