I've got a backbone model with contains a collection.
The output from the console when I do console.log(this.model)
is
d _changed: false _changing: false _escapedAttributes: Object _previousAttributes: Object attributes: Object cid: "c1" id: 63 itemlist: d _byCid: Object _byId: Object _onModelEvent: function () { [native code] } _removeReference: function () { [native code] } length: 5 models: Array[5] __proto__: o url: "user/63" __proto__: o
perfect! now, I want to get the itemlist
collection so I can do this.model.itemlist.each(render(item))
.
But when I try to output console.log(this.model.itemlist)
, I get an empty collection
d _byCid: Object _byId: Object _callbacks: Object _onModelEvent: function () { [native code] } _removeReference: function () { [native code] } length: 0 models: Array[0] parent: d __proto__: o
I'm not sure why this is, when I output the model, I can see the nested collection. why can't I get to the collection? or how can I get to the collection.
I create the nested collection via
user.fetch({ success: function(response){ user.itemlist = new itemlistcollection(response.items) } });
----------------- update -----------------
as @Paul help me to discover, the views are being triggered before the fetch function is completing, so I have the collection when I output from the fetch
, but I don't have the collection available int he view, which is where it is needed.
The fetch action is occuring in my router, I've created a function to initialize the object if it hasn't already been initialized (not sure how others to this. My router looks like this
User.Router = Backbone.Router.extend ({ routes: { "user/new": "newUser", "user/:id": "userView" "": "index" }, re_initialize: function(id){ user.fetch({ success: function(response){ user.itemlist = new itemlistcollection(response.items) } }); }, userView: function(){ console.log(user.itemlist); new User.View(user); } });