Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access data from controller in view in didInsertElement

Tags:

ember.js

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.

like image 251
gertruda Avatar asked Mar 25 '13 10:03

gertruda


1 Answers

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')
});
like image 116
Teddy Zeenny Avatar answered Oct 08 '22 23:10

Teddy Zeenny