Backbone: How to update a collection view when collection changes?

Viewed 21715

I'm relatively new to Backbone.js. I'm initializing a collection view and passing in a collection at creation time.

suggestionsView = new TreeCategoriesAutoSuggest.Views.Suggestions({
    collection: new App.Collections.Suggestions(this.getSuggestions(query))
});

I then render the collection view. Each time a user enters a query into a text box the collection is regenerated and assigned to the collection view using:

suggestionsView.collection.set(this.getSuggestions(query));

This takes care of the adding/removing of models in the collection but how do I manage the adding/removing of views for the added/removed models?

I should mention that I have used the this.collection.on("add") listener in the collection view. But this gets triggered for every model that is added. I also tried this.model.on("change") from within the individual view but this is not fired when models are added/removed from collections.

Any help/guidance appreciated!

Update

I am now using:

suggestionsView.collection.reset(this.getSuggestions(query));

And when the reset event is fired I'm removing the suggestion sub views, re-initializing them for the new collection and re-rendering the collection view.

handleReset: function(){
    console.log("reset");
    this.cleanupOldViews();
    this.initViews();
},

initViews: function(){
    this.collection.each(function(suggestion){
        this.suggestionViews.push(new TreeCategoriesAutoSuggest.Views.Suggestion({
            model: suggestion
        }));
    },this);        
},

cleanupOldViews: function(){
    _.each(this.suggestionViews,function(suggestionView){
        suggestionView.remove()
    },this);

    this.suggestionViews = [];
}

So you think I don't need to worry about destroying the models?

1 Answers
Related