3
votes

I have a filter working on my backbone collection. Type a search in the search box and the list live filters. Works great, or so I thought. When I looked at the memory heap snapshot in chrome, I can see the memory leaking with each search... 6 megs 8 megs... before long the heap snapshots are 100+ megs.

I have isolated the problem in the view below. If I comment out the this.listenTo in the initialize function I no longer seem to leak memory.

So my question is how do I keep these event listeners and the live filtering on the collection without leaking.

var View = Backbone.View.extend({

    tagName: 'tr',

    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    },

    events: {
        'click .edit': 'edit',
        'click .delete': 'delete',
    },

    edit: function() { /* EDIT */ },

    delete: function() {
        this.model.destroy(); //backbone
    },

    render: function () {
        var template = _.template( ProductTemplate )
        this.$el.html( template({ this.model.toJSON() }) )
        return this;
    }

})


var ListView = Backbone.View.extend({

    initialize: function()
    {
        this.collection = new Collection( Products ) //products are bootstrapped on load
    },

    render: function (terms)
    {
        this.$el.html( ListTemplate );

        var filtered = Shop.products.collection.search(terms)

        _.each(filtered, this.addOne, this)

        //append list to table
        $('#products').html( this.el )

        return this
    },

    addOne: function (product)
    {
        this.$el.find('tbody').append(
            new View({ model: product }).render().el
        )

        return this
    },

});

var Collection = Backbone.Collection.extend({

    model: Model,

    search : function(letters){

        //set up a RegEx pattern
        var pattern = new RegExp(letters,"gi")

        //filter the collection
        return this.filter(function(model)
        {
            if(letters == "") return true //if search string is empty return true
            return pattern.test(model.attributes['Product']['name'])
        });
    }


});

SOLVED:

This is my new search method. I am no longer filtering the collection and re-rendering. I simply loop over the collection, and if a model matches the search we trigger a 'show' event, if it is not in the search we trigger a 'hide' event. Then we subscribe to these events in the view and act accordingly.

search function from the collection: search : function(query){

    //set up a RegEx pattern
    var pattern = new RegExp(query,"gi")

    //filter the collection
    this.each(function(model){
      if ( pattern.test(model.attributes['Product']['name']) ){
        model.trigger('show')
      }
      else{
        model.trigger('hide')
      }
});
}

The new view: var ProductView = Backbone.View.extend({

    tagName: 'tr',

    initialize: function() {
        this.listenTo(this.model, 'show', this.show);
        this.listenTo(this.model, 'hide', this.hide);
    },

    hide: function()
    {
      this.$el.addClass('hide')
    },

    show: function()
    {
      this.$el.removeClass('hide')
    },

    render: function ()
    {
        var template = _.template( ProductTemplate )
        this.$el.html( template( {data: this.model.toJSON(), Utils: Shop.utils} ) )
        return this;
    }

});
1
So you create a lot of View instances but never call remove on them?mu is too short
so I know my problem is that I am creating endless views and never closing them. I'm just trying to come up with a good method for tracking the views, so that I can close them. Or as @anshr suggested below simply hide/show them based on query. Such a method has eluded me so far.Neil Holcomb

1 Answers

4
votes

To expand on what @mu already commented on, you're not removing views that you've created. They're not in the DOM, but they're still hanging around in memory because they have a reference to your models (therefore, the garbage collector will not remove them for you).

You have a couple options:

  1. Keep track of all the views that are being instantiated by addOne and remove them each time render is called.
  2. Make your code show/hide views rather than instantiate/destroy each time the filter criteria is changed. This is more work, but is certainly the more optimal solution.