1nfiniti
1nfiniti

Reputation: 2070

Nested Collection/Model View management in Backbone.js

I was wondering about some general best practices in Backbone.js for managing sub-model views within a collection.

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 & refining my 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);
        });
    }

});

I usually implement this by extending the CollectionView Class. Something like

MyView = CollectionView.extend({

    el: '#id',
    viewPointers: {}, // reference to individual itemViews by model CID
    itemView: views.SingleItem,

    ...

    initialize: function() {
        this.renderCollection();
    },

});

Does anyone else have something they like to use for this situation?

Upvotes: 2

Views: 1535

Answers (1)

ekeren
ekeren

Reputation: 3458

I have dealt with the same issues, a lot of boilerplate code that feels stupid and generates tons of memory leaks.

You should use Marionette.js, especially Marionette.CollectionView/CompositeView for your collection view and Marionette.ItemView for your items.

The beauty of Marionette is that you don't need to change your entire application structure, you can just change the hierarchy to extend Marionette objects for your specific need and it will do the work for you.

I am very satisfied with it, eventually I moved my entire application to use Marionette.js Objects.

Upvotes: 3

Related Questions