Reputation: 33
Can anyone tell me why my usersArr is not available to me in my Ember Route? See the alert called out below.
App.UsersIndexRoute = Ember.Route.extend({
setupController: function (controller, model) {
var usersArr = App.userService.findUsers(); // there are 10 items in this
var arrControl = Ember.ArrayController.create({
content: usersArr,
sortProperties: ['id'],
sortAscending: true
});
// begin: my test code
alert('usersArr.length: ' + usersArr.length); // displays "0"
// end: my test code
controller.set('currentPage', {label: 1, startItem: 0});
controller.set('content', arrControl);
}
});
The controller and the page shows the usersArr data just fine. BUT, I simply cannot figure out how to get access to it in the Route.setupController() method. I want to slice it for a sub template. Any ideas?
Upvotes: 0
Views: 91
Reputation: 8041
The reason you see the length as 0 because, when you do a find()
Ember
responds immediately with an object whose length is 0(promise), but in the background Ember
queries with the database and once the request is successful that object gets populated with the records.
It happens asynchronously i.e. javascript starts executing the rest of the lines in your method instead of waiting for the data to be loaded, but ember provides us isLoaded
flag to know when exactly the record has finished loading,so that we can combine that with an observer
to do stuff once the records are finished loading.
In your case I'd do
App.UsersIndexRoute = Ember.Route.extend({
setupController: function (controller, model) {
this.set('usersArr', App.userService.findUsers()); // there are 10 items in this
/* your code */
},
notify: function(){
alert(this.get('usersArr.length'));
}.observes("usersArr.isLoaded")
});
The reason it works fine inside templates is because, default handlebars helpers are binding aware, Ember
takes care about updating for us...
Upvotes: 1