[英]Sending action from component to route in ember.js
這是路線:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
closeModal: function () {
alert('asdf');
}
}
});
組件js代碼:
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
closeModal: function () {
this.sendAction('closeModal');
}
}
});
我想做的是(如代碼所暗示的那樣;))從組件到路由發送一個動作,以便路由可以對其進行操作。 但是上面的代碼不起作用 - 組件正確處理動作,但是它的方法中的sendAction
調用沒有做任何事情。
編輯:
我解決了這個問題:
this._controller.send('closeModal');
在組件的動作方法中,然而這個解決方案並不滿足我。 Ember的作者說在ember 2.0中將刪除控制器,因此在我的代碼中我不想對它們進行任何引用。 建議?
組件具有隔離的上下文。 因此它對組件外部的任何事物(路由或控制器)一無所知。 為了將組件中的操作發送到您的路徑,您應該將路徑的操作傳遞給模板中的組件,如下所示:
// your template
{{your-component closeModal="closeModal"}}
現在,當您在組件中調用this.sendAction('closeModal')
時,它將觸發模板中組件的操作,在本例中是您的路徑的closeModal
操作。
有關更多信息,請參閱文檔( http://emberjs.com/api/classes/Ember.Component.html#method_sendAction )
更新2016年8月3日
對於那些在較新版本的Ember中遇到關閉操作的人,您也可以通過以下方式在此處使用此類操作:
// your template
{{your-component closeModal=(action "closeModal")}}
此操作助手將指向控制器的操作,您可以在組件中調用this.attrs.closeModal()
或this.get('closeModal')()
來觸發操作而不是調用sendAction
。
這些操作的好處是操作可能返回一個可以在組件中使用的值。 在模態的情況下,這可以例如用於確定是否可以在調用closeAction
關閉模態,如果它返回false
,例如你可能決定阻止模態關閉。
作為旁注,關閉操作始終指向您的控制器,為了讓它指向路由操作,您可以查看此插件: https : //github.com/DockYard/ember-route-action-幫手
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.