B Robster
B Robster

Reputation: 42043

Backbone.js: Is there a way to set a property for all models in a collection when creating the collection

I am wondering if there is any way to pass in a value when I instantiate a new Collection, which will be set as a property on all new models that are added to the collection. E.g.,

allSchools = [/* list of schools */];
this.schoolTypes = new Backbone.Collection([], { model:SchoolType }); //pass in allSchools here, somehow
this.schoolTypes.add({name:'New SchoolType'});

where the newly added Model will have a this.allSchools (or this.options.allSchools or something like that). Seems there should be a simple enough way to do this? Currently I'm just accessing a global allSchools object but its not very modular.

Upvotes: 0

Views: 1151

Answers (2)

B Robster
B Robster

Reputation: 42043

As mu mentioned in his comment, models have a built-in .collection property. So, if I set a property on the collection, I can access it from any model within the collection like so:

schoolType = schoolTypes.at(0);
allSchools = schoolType.collection.allSchools;

Upvotes: 0

gion_13
gion_13

Reputation: 41533

It may not be the best way, but you could add a backward link to the model to let it access it's parent collection :

this.schoolType.allSchools = allSchools;
var col = this.schoolType;
this.schoolType.each(function(el,i){
    el.collection = col;
});
// ...
// then access all the schools from your SchoolType model `m` : 
if(m.collection)
    var allSchools = m.collection.allSchools;

Upvotes: 1

Related Questions