ValeriiVasin
ValeriiVasin

Reputation: 8706

How to add more than one model/collection to the Backbone View?

When I add collection to the view like this:

var View = new MyCollectionView({ collection: new MyCollection() });

everything is okey. I can use this collection in initialize method (for binding events, for example). But how can I add another one?

I can't do this way:

var View = new MyCollectionView({
  collection: new MyCollection(),
  secondCollection: new MySecondCollection()
});

Upvotes: 0

Views: 1562

Answers (1)

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

constructor / initialize new View([options])

There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

So, if you create a view like this:

new View({collection: c})

then Backbone will automatically assign c to the view's this.collection. But if you create the view like this:

new View({collection: c, secondCollection: c2})

then inside the View's constructor:

initialize: function(options) {
    // this.collection will be 'c' from above
    // options.secondCollection will be 'c2'
}

So you can do this:

var View = new MyCollectionView({
  collection: new MyCollection(),
  secondCollection: new MySecondCollection()
});

provided that your MyCollectionView has an initialize method that knows to pull the secondCollection out of its options argument.

Open your JavaScript console and have a look at what this does:

var V = Backbone.View.extend({
    initialize: function(options) {
        var c1 = options.collection;
        var c2 = options.secondCollection;
        console.log(this.collection);
        console.log(c1);
        console.log(c2);
    }
});
var view = new V({collection: 1, secondCollection: 2});

Demo: http://jsfiddle.net/ambiguous/XyeSD/

Upvotes: 7

Related Questions