[英]How do I call a controller action from an Ember route while doing a transition?
我的目標是在我的頁面上顯示一個花哨的“loading ...”圖形,而Ember通過Ember路線獲取模型數據。
這導致我http://emberjs.com/guides/routing/loading-and-error-substates/ 。 這激發了我在我的頁面控制器上創建一個動作,它將在DOM中顯示“加載”覆蓋窗口。 例如,這是我的控制器:
控制器/ users.js:
export default Ember.ArrayController.extend({
...
actions: {
displayLoading: function() {
// Show the DOM element that says "Loading..."
},
...
}
});
我想在我的數據加載時調用它,所以我然后定義一個路由如下:
路線/ users.js:
export default Ember.Route.extend({
model: function( params ) {
return this.store.find('user', params );
},
actions: {
loading: function(transition, originRoute) {
transition.send('displayLoading');
}
}
});
但是,當我這樣做時,我收到此錯誤:
Uncaught Error: Nothing handled the action 'displayLoading'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.
所以我的問題是我在哪里可以定義這個動作,以便我的loading
方法能夠調用它?
請注意,嘗試this.send('displayLoading')
給了我這個錯誤:
Can't trigger action 'displayLoading' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call .send() on the Transition object passed to the model/beforeModel/afterModel hooks.
。
更新:我能夠在路線本身上捕捉到這個動作,但是我仍然無法在我的控制器上調用該動作。
更新#2:感謝@ kingpin2k的回答,我已經解決了這個問題。 對於那些感興趣的人,這是一個完整的解決方
控制器/ users.js:
export default Ember.ArrayController.extend( {
actions: {
showLoading: function() {
this.set('isLoading', true);
},
hideLoading: function() {
this.set('isLoading', false);
},
}
});
路由器/ 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');
}
}
});
一個關鍵的見解是我可以在我的控制器上設置一個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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.