7

我正在使用 Ember 2.2.0

在编写组件时,我曾经使用this.sendAction(…). 我最近查看了文档,发现他们建议了另一种方法。 https://guides.emberjs.com/v2.2.0/components/triggering-changes-with-actions/

this.get('action')();

由于 Ember 以非常固执己见而著称,因此我希望尽可能坚持最佳实践。但我不确定文档是否可能已过时,或者使用 sendActions 的教程是否已过时。

所以我想这样做的方法是什么?

4

2 回答 2

14

当您使用时,this.sendAction('actionName')您正在冒泡一个动作,您必须使用它来捕捉组件/控制器actions

//controller/route/component.js
actions: {
  actionName: function() {
    //Do something
  }
}

如果你想把它发送到链上,你必须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
     });
  }
}

关于闭包动作可以写很多,但其他人写得比我好得多,所以我推荐以下文章:

如果您对整个 DDAU(Data Down Actions Up)概念不熟悉,我真的推荐Sam关于该概念的文章。

更新:还有一个插件(由@locks 在评论中链接)允许关闭操作冒泡到 routes。请注意,如果您希望将 Ember 升级到更新的版本(3.8 及更高版本),route-actions 将不兼容。

于 2016-01-11T18:53:14.570 回答
1

对于使用 Ember 版本 >=3.4 的用户:

使用关闭操作而不是sendAction

sendAction在 3.4 中弃用。您可以在相关的弃用文本下找到如何定义关闭操作的示例:

https://deprecations.emberjs.com/v3.x/#toc_ember-component-send-action

于 2020-02-04T22:28:43.923 回答