can't access backbone collection through object notation
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); } });
It might be a race condition since fetch
is an asynchronous method.
Have you confirmed fetch
has processed the request from the server before you call this.model.itemList
?
To confirm this, add a console log message in the fetch method
user.fetch({
success: function(response){
user.itemlist = new itemlistcollection(response.items)
console.log(user.itemList)
}
});
UPDATE
If you want the view to render the collection after it has been fetched, you trigger a 'fetched' event on your model, and have the view bind to this event to render the collection.
Here is an example of how you can update your code
user.fetch({
success: function(response){
user.itemList = new itemlistcollection(response.items);
user.trigger('fetched');
}
});
yourView = Backbone.View.extend({
initialize: function() {
this.model.bind('fetched', this.renderList, this);
},
renderList: function() {
this.model.itemList.each(render(item));
}
}
链接地址: http://www.djcxy.com/p/53364.html
上一篇: 如何使用Backbone.js在模型上设置动态属性
下一篇: 不能通过对象表示法访问骨干网络