在didInsertElement中从视图中访问控制器中的数据

ger*_*uda 5 ember.js

我试图从DashboardIndexView中的DashboardIndexController访问数据

JP.DashboardIndexController =  Ember.Controller.extend({
  users: []
});
Run Code Online (Sandbox Code Playgroud)

是否可以在didInsertElement中访问JP.DashboardIndexView中的用户?

didInsertElement : function(){
    console.log(this.get("controller.users").objectAt(0));
}
Run Code Online (Sandbox Code Playgroud)

这是我的DashboardIndexRoute:

JP.DashboardIndexRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    controller.set('users',  JP.User.find());
  }
});
Run Code Online (Sandbox Code Playgroud)

谢谢

编辑

console.log(this.get("controller.users").objectAt(0));
Run Code Online (Sandbox Code Playgroud)

只有当我转到UsersIndex然后回到DashboardIndex... 时才返回数据.我认为它是初始化的东西,但我不知道,如何解决它.

Ted*_*nny 9

是的,这是访问用户列表的方法.

发生这种情况是因为在使用来自服务器的数据填充DashboardIndexView之前将其插入DOM controller.users.

因此,当呈现视图时,controller.users仍然为空,并且在ajax请求完成后将异步填充,问题didInsertElement已经被触发.

为了解决这个问题,您需要controller.users从另一个钩子访问. DidInsertElement是错误的地方,因为无论是否JP.User.find()装完,它都会开火.

您只需要确保在JP.User.find()加载时重新触发,即使视图已经在DOM中.像这样的东西:

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')
});
Run Code Online (Sandbox Code Playgroud)