max*_*rus 6 ember.js ember.js-2
我使用的是Ember 2.2.0
在编写组件时,我曾经将事件从组件传播到路由(或者嵌入组件的任何东西)this.sendAction(…).我最近检查了文档并发现他们建议另一种方法.
https://guides.emberjs.com/v2.2.0/components/triggering-changes-with-actions/
this.get('action')();
Run Code Online (Sandbox Code Playgroud)
由于已知Ember非常自以为是,我希望尽可能多地遵循最佳实践.但我不确定文档是否过时或使用sendActions的教程是否过时.
所以我想要这样做的方法是什么?
Ped*_*Rio 11
当你使用时,this.sendAction('actionName')你正在冒充一个你必须在组件/控制器上捕获的动作actions
//controller/route/component.js
actions: {
actionName: function() {
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想在链中发送它,你将不得不sendAction('')再次在组件/控制器上调用并在父节点上再次捕获它(依此类推).
另一种方法this.get('action')()使用闭包动作,这是常规的javascript函数.据我所知,这些是在Ember 1.13.X中调用操作的首选方法.关闭动作的一个巧妙之处是你可以拥有返回值.这意味着你可以拥有这样的东西:
//a controller
actions: {
saveResult() {
return this.get('model').save(); //notice the return (which returns a promise)
}
}
//some template that uses the controller above
{{a-component save=(action 'saveResult')}} // Passes the saveResult action to the component
//a-component.js
actions: {
someAction: function() {
this.attrs.save().then(() => {
//Do something with the return value
});
}
}
Run Code Online (Sandbox Code Playgroud)
关于闭包动作可以写很多,但其他人写得比我好得多,所以我推荐以下文章:
如果你是整个DDAU(Data Down Actions Up)概念的新手,我真的推荐Sam关于这个概念的文章.
更新:还有一个插件(在@locks的评论中链接)允许关闭操作冒泡到路由.