6
votes

Is there any way to listen to remove/destroy event on the Backbone View.?

I want to do some thing like as below:

$(myBackboneView).on('remove', function () {
    // do some processing
});

or

$(myBackboneView).on('destroy', function () {
    // do some processing
});

Thank you in advance. :)

3
Yes, I need to do some processing before the view is completely removed.Rahul Bhanushali

3 Answers

8
votes

You can try to override the View.remove method::

Backbone.View.extend({
    remove: function(){
        // Your processing code here

        Backbone.View.prototype.remove.apply(this, arguments);
    };
});
1
votes

I tried the following and it works for me:

$(myBackboneView.el).on('remove', function () {
    // do some processing
});

Is this is a good approach ? Or there is something else better than this?

0
votes

If you need to listen for other views being removed, you can have your base View class trigger a 'remove' event when remove() is called.

BaseView = Backbone.View.extend({
    remove: function () {
        this.trigger('remove', this)
        return Backbone.View.prototype.remove.apply(this, arguments)
    }
})

Then listen for that whenever you like:

this.listenTo(otherView, 'remove', func)