Note that there are some explanatory texts on larger screens.

plurals
  1. PONested Collection/Model View management in Backbone.js
    text
    copied!<p>I was wondering about some general best practices in Backbone.js for managing sub-model views within a collection. </p> <p>To date, I've been using the solution below. Just wondering if anyone else had a take on this, or a better way of handling it. It's worked well for me so far, but I'm always interested in learning more &amp; refining my code.</p> <pre><code>CollectionView = Backbone.View.extend({ renderItem: function(model) { // instantiate view for an item this.viewPointers[model.cid] = new this.itemView({ model: model }); this.$(".item-list").append( this.viewPointers[model.cid].render().el ); }, renderCollection: function() { // instantiate views for entire collection var self = this; this.removeAll(); // clear current references (if any exist) this.collection.each(function(model){ self.renderItem(model); }); }, removeItem: function(model) { // remove/delete an individual view object this.viewPointers[model.cid].undelegateEvents(); this.viewPointers[model.cid].remove(); delete this.viewPointers[model.cid]; }, removeAll: function() { // remove/delete entire collection's view objects var self = this; _.each(this.viewPointers, function(view) { self.removeItem(view.model); }); } }); </code></pre> <p>I usually implement this by extending the CollectionView Class. Something like</p> <pre><code>MyView = CollectionView.extend({ el: '#id', viewPointers: {}, // reference to individual itemViews by model CID itemView: views.SingleItem, ... initialize: function() { this.renderCollection(); }, }); </code></pre> <p>Does anyone else have something they like to use for this situation?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload