Reputation: 2465
I'm having a hard time figuring out how best to do this. I have a model that instantiates a few collections in its initialize method. Immediately after instantiating that model, I need to get a model in one of those collections but at the time I try to get that model it seems to not be available so I end up getting 'undefined' instead. This is what I have:
var App = Backbone.Model.extend({
initialize: function() {
this.users = new Users();
}
});
app = new App();
someUser = app.users.get("someuserID"); // -> undefined
But if I do:
var App = Backbone.Model.extend({
initialize: function() {
this.users = new Users();
}
});
app = new App();
setTimeout(function(){
someUser = app.users.get("someuserID"); // -> user instance
},3000);
I tried adding a this.trigger("loaded")
to the App initialization method and then listening for that event but the event doesn't trigger. Like so:
var App = Backbone.Model.extend({
initialize: function() {
this.users = new Users();
this.trigger("loaded");
}
});
app = new App();
app.on("trigger",function(){ // -> never actually triggers
someUser = app.users.get("someuserID");
});
Any ideas?
Note that the Users collection IS fetching the users correctly from a restful API.
Thank you,
Luis
Upvotes: 0
Views: 456
Reputation: 3619
When the collection has completed the .fetch
, it will fire a reset
event, per the Backbone documentation. You haven't included your Users
class here, but assuming it's just a Collection and not a wrapper for one, you'd do the following:
var App = Backbone.Model.extend({
initialize: function() {
this.users = new Users();
}
});
app = new App();
app.users.on('reset',function() { var someUser = app.users.get("someuserID"); });
Upvotes: 1