Thomas Blom
Thomas Blom

Reputation: 103

Best Practice CollectionView pattern in Backbone.js?

Many Backbone.js examples and tutorials illustrate displaying a collection of models by having a CollectionView which, in its own render() function, loops over the items and creates a new ItemView for each model (each of which are then rendered).

This means you can't just call render() on your collection when something about it changes - you have to take care to destroy/unbind the previous views first.

This complete tear-down/rebuild of view objects feels heavy-weight when an otherwise simple approach to listview-management is to say "when something about this list changes, re-render it". A more complicated (if perhaps more efficient) approach is responding to particular events more specifically (e.g. "item selected") and tweaking individual item views.

Is there a conventional wisdom about this for working with collections of models?

Upvotes: 0

Views: 172

Answers (1)

ne8il
ne8il

Reputation: 2427

If you are willing to add another library to your mix, the Backbone.Marionette project adds a few classes to deal with the complexity of collection views and managing view hierarchy :

https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md

If you provide a Collection to a CollectionView, it will stay in sync and add/remove individual child views as the Models in the Collection are added or removed. I have found it to help immensely.

If you want to keep using pure Backbone, you could still look at the source for Marionette's CollectionView to see some general convention, but you will probably end up rewriting a lot of that functionality.

Upvotes: 2

Related Questions