I have a backbone collection on the client.
Model of the collection has some properties along with another collection
When I do fetch() my action method on the server returns some data, collection gets populated, all the properties too, except that nested collection.
What could be the reason?
var Job = Backbone.Model.extend();
var Jobs = Backbone.Collection.extend({model: Job})
var Foo = Backbone.Model.extend({
initialize:function(){
this.jobs = new Jobs();
}})
var FooCollection = Backbone.Collection.extend({model: Foo})
var fooCol = new FooCollection()
fooCol.fetch();
fooCol.first().get('name') // => returns name
fooCol.first().jobs.toJSON() // returns nothing
// although this will
fooCol.first().get('jobs') //it will return an array
So somehow nested Backbone collection becomes just a regular property (Array)
OK – with your extra information, I can give you an answer.
First – “get” doesn’t get a property off of the model. It gets a property off of the model’s
attributesproperty. So, the attributes probably look like:Backbone doesn’t automagically transform arrays into collections and models, and simply setting
this.jobsisn’t going to work. What you need to do is a little more complex.This will set your ‘jobs’ property to a new jobs object with the data that was sent over for the jobs. But, alas, it won’t automatically fire events on the Jobs collection, nor will it allow you to use helpers like
this.get('jobs').each(fn);– you’ll only be able to use it asFoo.jobs.each(fn).In order for you to use the attribute as an actual collection, you’ll have to do a lot more complicated things.
Note that this is completely untested, but hopefully it shows some of the way you’d do this.