Ember.js 从didInsertElement视图中的控制器访问数据
我正在尝试从DashboardIndexView中的DashboardIndexController访问数据Ember.js 从didInsertElement视图中的控制器访问数据,ember.js,Ember.js,我正在尝试从DashboardIndexView中的DashboardIndexController访问数据 JP.DashboardIndexController = Ember.Controller.extend({ users: [] }); 是否可以访问didInsertElement中JP.DashboardIndexView中的用户 didInsertElement : function(){ console.log(this.get("controller.user
JP.DashboardIndexController = Ember.Controller.extend({
users: []
});
是否可以访问didInsertElement中JP.DashboardIndexView中的用户
didInsertElement : function(){
console.log(this.get("controller.users").objectAt(0));
}
这是我的仪表板IndexRoute:
JP.DashboardIndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
controller.set('users', JP.User.find());
}
});
多谢各位
编辑
console.log(this.get("controller.users").objectAt(0));
仅当我转到
UsersIndex
然后返回到DashboardIndex
时才返回数据。。。我认为这与初始化有关,但我不知道如何修复它。是的,这是访问用户列表的方法
这是因为仪表板IndexView
在控制器之前插入到DOM中。用户使用来自服务器的数据填充
因此,在呈现视图时,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')
});
我在usersChanged
中获取计算属性时遇到问题。this.get('controller').get('model').get('length')
显示已加载模型,但this.get('controller').get('total')
(计算属性)返回NaN。有什么想法吗?而且,每次加载用户时都会触发。加载所有用户时是否有触发器?谢谢我没有足够的信息来回答你的第一个问题。对于第二个问题,您可以尝试使用Ember.run.once
来调度该方法;看,谢谢!如果你感兴趣的话,我还问了另一个问题:这对我仍然不起作用。当观察者激发时,模型尚未加载到视图中。您知道在视图中渲染模型更改后,是否有方法观察模型更改?