I am trying to access data from DashboardIndexController in DashboardIndexView
JP.DashboardIndexController = Ember.Controller.extend({
users: []
});
Is it possible to access users in JP.DashboardIndexView in didInsertElement?
didInsertElement : function(){
console.log(this.get("controller.users").objectAt(0));
}
This is my DashboardIndexRoute:
JP.DashboardIndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
controller.set('users', JP.User.find());
}
});
Thank you
EDIT
console.log(this.get("controller.users").objectAt(0));
Returns data only when I go to UsersIndex
and then back to DashboardIndex
... I think it's something with initialization, but I don't know, how to fix it.
Yes, this is how to access the list of users.
This happens because the DashboardIndexView
is inserted into the DOM before the controller.users
is populated with data from the server.
So when the view is rendered, controller.users
is still empty, and will asynchronously be populated after the ajax request finishes, problem is, didInsertElement
already fired.
In order to solve this, you need to access controller.users
from another hook. DidInsertElement
is the wrong place, because it will fire irrespective of whether JP.User.find()
finished loading.
You just need to make sure that it re-fires when JP.User.find()
is loaded even if view is already in the DOM. Something like this:
JP.DashboardIndexView = Ember.View.extend({
didInsertElement: function() {
this.usersChanged();
},
usersChanged: function() {
if (!this.$()) { return; } // View not in DOM
console.log(this.get('controller.users'));
}.observes('controller.users.@each')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With