0

I am creating a backbone view with custom events. If I remove the backbone view, the remove process unsubscribe the events or I have to manually unsubscribe the events.

Similarly, I created a master view with some child views. If I remove the master view, will all my child events will unsubscribe or I have to unsubscribe the child events and unsubscribe the master view events.

Please suggest me an approach where I can remove the views in a proper order so that no memory leaks will happen.

Jackman
  • 157
  • 8
  • It depends on how you declare your event and how you subscribe to them. If you use [listenTo](http://backbonejs.org/#Events-listenTo) then when you remove the view they should be removed as well. Have a look at this answer http://stackoverflow.com/a/14042632/384985 from [Derick Bailey](http://stackoverflow.com/users/93448/derick-bailey) – Jack Jan 23 '14 at 20:39

1 Answers1

0

You need call remove() method for each of your child views and then call native remove() method on your view. Native remove will stop listening to events and remove $el from the DOM.

Here is an example:

var View = Backbone.View.extend({

    initialize: function() {
        this.views.my_view_1 = new Backbone.View();
        this.views.my_view_2 = new Backbone.View();

        return this;
    },

    /*
     *  Remove child views and remove itself
     */
    remove: function() {
        // Remove the child views
        Object.keys(this.views).forEach(function(view_name) {
            if (is(this.views[view_name].remove, "function")) {
                this.views[view_name].remove();
            }
        }, this);

        // Call the native remove function.
        Backbone.View.prototype.remove.apply(this, arguments);

        // For old browsers we need convert arguments object to Array
        // Backbone.View.prototype.remove.apply(this, Array.prototype.slice.call(arguments));

        return this;
    }

});
Eugene Glova
  • 1,543
  • 1
  • 9
  • 12