简体   繁体   中英

unbinding backbone events with unbind

If I have an event aggregator on an object,

eventAggregator: _.extend({}, Backbone.Events),

and for a modal view, I basically have the presenter of the modal view listen for an event of the modal view.

this.eventAggregator.on('modal:close', function () {
console.log('do some clean up');
});

When the modal view goes away, I call

this.unbind(); 

Does that remove all of the events? Or do I need to do something like

this.eventAggregator.off('modal:close');

Thanks in advance!

In the recent Backbone there is listenTo ( http://backbonejs.org/#Events-listenTo ) so you can subscribe to events this way:

this.listenTo(this.eventAggregator, 'modal:close', function () {
    console.log('do some clean up');
})
this.listenTo(this.model, 'change', this.doSomeStuff);

Then if you need to unsubscribe, simply call this:

this.stopListening();

Or remove your view with view.remove ( http://backbonejs.org/#View-remove ), it will call view.stopListening under the hood.

o.unbind() won't know anything about objects inside o , it only knows about things bound to to o using o.on (AKA o.bind ). So no, this.unbind() won't do anything about things bound to this.eventAggregator , you'd have to:

this.eventAggregator.unbind();
this.unbind();

to clear out both lists.

If you want to use on/off for binding/unbinding of events you can probably do this.

//declare some global object to get the scope.
window.eventAggregator = _.extend({}, Backbone.Events);

now in the backbone view:

var SomeView = Backbone.View.extend({
    el : 'body',
    initialize : function() {

        //pass the context as this object
        eventAggregator.on('modal:close', function(data) {
            console.log('Clean up');
            eventAggregator.off('modal:close', null, this);
        }, this);
    }
});

eventAggregator.off('modal:close', null, this); it will help you to turn off the event bound to 'this' current view object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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