我的目标是在 Ember 通过 Ember 路由获取模型数据时在我的页面上显示一个奇特的“正在加载...”图形。
这让我找到了 http://emberjs.com/guides/routing/loading-and-error-substates/ .这启发了我在我的页面 Controller 上创建一个 Action ,该 Action 将在 DOM 中显示“正在加载”覆盖窗口。例如,这是我的 Controller :
controllers/users.js:
export default Ember.ArrayController.extend({
...
actions: {
displayLoading: function() {
// Show the DOM element that says "Loading..."
},
...
}
});
我想在加载数据时调用它,因此我定义了一个路由,如下所示:
routes/users.js:
export default Ember.Route.extend({
model: function( params ) {
return this.store.find('user', params );
},
actions: {
loading: function(transition, originRoute) {
transition.send('displayLoading');
}
}
});
但是当我这样做时,我得到了这个错误:
未捕获错误:没有处理操作“displayLoading”。如果您确实处理了该操作,则此错误可能是由于从 Controller 中的操作处理程序返回 true 导致操作冒泡。
所以我的问题是我在哪里可以定义这个 Action ,以便我的loading
方法能够调用它?
请注意,尝试 this.send('displayLoading')
给了我这个错误:
无法触发操作“displayLoading”,因为您的应用尚未完成转换到其第一条路线。要在转换期间触发目标路由上的操作,您可以在传递给 model/beforeModel/afterModel Hook 的 Transition 对象上调用 .send()。
。
更新:我能够在路线本身上捕捉到这个 Action ,但是我仍然无法在我的 Controller 上调用这个 Action 。
更新#2:感谢@kingpin2k 的回答,我已经解决了这个问题。对于那些感兴趣的人,这是一个完整的解决方案:
controllers/users.js:
export default Ember.ArrayController.extend( {
actions: {
showLoading: function() {
this.set('isLoading', true);
},
hideLoading: function() {
this.set('isLoading', false);
},
}
});
routers/users.js:
export default Ember.Route.extend({
model: function( params ) {
return this.store.find('user', params );
},
actions: {
loading: function() {
this.controllerFor('users').send('showLoading');
},
didTransition: function() {
this.controllerFor('users').send('hideLoading');
}
}
});
一个重要的见解是,我可以在我的 Controller 上设置一个 isLoading
属性,它确定我的模式“正在加载...”窗口是否显示在 Handlebars 模板中。
最佳答案
使用 controllerFor
, http://emberjs.com/api/classes/Ember.Route.html#method_controllerFor
loading: function(transition, originRoute) {
var controller = this.controllerFor('foo');
controller.send('displayLoading');
}
关于javascript - 如何在进行转换时从 Ember 路由调用 Controller 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25333730/