Question

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. :)

Was it helpful?

Solution

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);
    };
});

OTHER TIPS

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?

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top