Search code examples
backbone.jsbackbone-viewsbackbone.js-collectionsbackbone-model

Backbone JS - Combination of collection, views and models


I had the following setup now in three different projects, so I thought maybe it's worth asking here. There's a chance I'm not the only person wondering about this.

So there it comes:

  • I have a list of objects
  • The list items have a special function like draggable or onClick-Events

My question: How do I build this scenario with Backbone?

I guess I create a model and a view for my list objects. I use a collection for keeping together my objects.

Now I wonder: Do I instantiate the object view in the model constructor and instantiate the models in the collection constructor? Or is there a better way to achieve what I want?


Solution

  • Neither; use a mediator to instantiate the views and inject them with their model/collection.

    Marionette.js has a nice implementation for this sort of mediating object, called Controller - I suggest you check it out.

    Further more, you don't have to explicitly instantiate the collection models - just declare their type in the collection's prototype, e.g.:

    var MyModel = Backbone.Model.extend({
        // do some shit
    });
    
    var MyCollection = Backbone.Collection.extend({
        model: MyModel // pass the type for the collection to instantiate
    });
    

    Taking our mediator/controller approach further, this is how it could be done (with Marionette.js):

    var MyController = Marionette.Controller.extend({
        initialize: function () {
            this.myCollection = new MyCollection();
            this.myCollectionView = new MyCollectionView({
                collection: this.myCollection
            });
        }
    });
    

    This, of course, is just a skeleton code, meant to roughly demonstrate the MVC approach, but it's a good starting point.