【问题标题】:Ember Communication Between Components组件之间的 Ember 通信
【发布时间】:2015-08-25 17:12:17
【问题描述】:

我正在开发一个 web 应用程序来显示和搜索文档。我已经像这样布置了主要的包装器 div:

<div class="wrapper">
    {{searchComponent searchComponent=searchComponent}}
    {{pdfViewer pdfSearchComponent=searchComponent}}
</div>

这允许我稍后在其中添加其他类型的查看器,如下所示:

{{otherViewer otherSearchComponent=searchComponent}}

外包装也是一个 ember 组件。所以它的控制器看起来像:

Ember.controller.extend({
   searchComponent: null,
   .
   .
   otherProperties,
   actions: { }
});

搜索组件在初始化时绑定自身,受此来源的启发:http://www.samselikoff.com/blog/getting-ember-components-to-respond-to-actions/

Ember.controller.extend({
    searchComponent: null,
    .
    .
    onStart: function(){
       this.searchComponent = this;
    }.on('init'),
    .
    .
    actions: {
        someAction: function() {
            //do something
        }
    }
}

所以我现在可以像这样从主 pdfViewer 引用组件:

this.get('searchComponent').send('someAction')

为了获得响应,我现在将另一个属性绑定到所有控制器/模板,然后在查看器控制器中观察该属性的更改,之后我可以将结果放置在需要的位置。

有没有办法从我的“pdfViewer”向我的“searchComponent”发送“消息”并接收“响应”而无需像上面那样明确地将它们绑定在一起?

【问题讨论】:

  • 不,当然它们在您的实现中也是紧密耦合的,也许其中一个应该消耗另一个而不是它们作为兄弟姐妹。或者也许其中一个的结果应该绑定为依赖组件上的属性

标签: ember.js handlebars.js


【解决方案1】:

您可以考虑通过 Service 事件总线使用 pub/sub,其中您的 searchComponentpdfViewer 都发出和侦听消息,因此可以相互交谈。当然,对服务有依赖关系,但据我所知,您的组件无论如何都是非常特定于应用程序的。

类似:

_listen: function() {
  this.get('eventBus').on('message', this, 'handleMessage');
}.on('init'),

actions: {
  click() { this.get('eventBus').trigger('message', message); }
}

几周前,我评估了几种父子组件通信的方法:http://emberigniter.com/parent-to-children-component-communication/,也许这会有所帮助。

【讨论】:

  • 我看了你的帖子。这是一个有趣的阅读!感谢您的解决方案!
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 2014-12-21
  • 2019-05-30
  • 2016-06-09
  • 2015-09-18
  • 2016-05-01
  • 2017-09-04
  • 2021-03-02
相关资源
最近更新 更多