我正在使用Ember 2.2.0
在编写组件时,我曾经使用this.sendAction(…)
将事件从组件传播到路由(或嵌入组件的任何东西)。我最近检查了一下文档,发现他们建议另一种方法。
https://guides.emberjs.com/v2.2.0/components/triggering-changes-with-actions/
this.get('action')();
由于Ember众所周知,所以我想尽可能地坚持最佳实践。但是我不确定文档是否过时或使用sendActions的教程。
所以我想怎么做呢?
最佳答案
当您使用this.sendAction('actionName')
时,您正在冒一个 Action ,您必须使用actions
捕获组件/ Controller
//controller/route/component.js
actions: {
actionName: function() {
//Do something
}
}
如果要沿链发送,则必须在组件/ Controller 上再次调用sendAction('')
,然后在父级上再次捕获它(依此类推)。另一种方法
this.get('action')()
使用闭包 Action ,这是常规的javascript函数。据我所知,这些是在Ember 1.13.X中调用 Action 的首选方式。闭合 Action 具有的一件整洁的事情是您可以拥有返回值。这意味着您可以拥有以下内容://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
});
}
}
关于关闭 Action ,可以写很多东西,但是其他人写得比我写的要好得多,因此,我推荐以下文章:如果您是整个DDAU(数据下降 Action 向上)概念的新手,我真的建议您就该概念总体上使用Sam's article。
更新:还有一个插件(通过@locks在注释中链接),该插件允许closure actions to bubble to routes。请注意,如果您希望将Ember升级到最新版本(3.8及更高版本),则
route-action
将不兼容。
关于ember.js - 在组件中使用this.sendAction()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34728522/