Ember 路由与不相关组件的通信

Ember route communication with unrelated component

我知道 EmberJS 促进 "data down, actions up",但我有一个场景,我不确定如何适应该范例。最好用一个与我要实现的目标类似的例子来解释。

假设我有一个固定的 header 组件 ('fixed-header')。我希望此 header 始终出现,因此我当然将其添加到我的主应用程序模板中:

{{fixed-header}}
{{outlet}}

现在假设我希望 header 显示有关我所在路线的一些信息。为简单起见,假设每条路线都有一个我希望显示在固定 header 中的标题。因此,无论我在 /foo/foo/bar/baz 还是 /wackawacka/meh?cat=meow 上,我都希望该路由能够将一些数据发送到 fixed-header 组件以进行显示。换句话说,我有点想反对 "data down" 并做 "data up".

解决这个问题的理想方法是什么?我的第一直觉是创建一个 my-header 监听的服务,并将他们的信息 post 路由到。但这是正确的做法吗?创建一个服务只是为了发送一点文本对我来说似乎很奇怪。还有别的办法吗?

服务才是王道。参考 Service Ember Guide

An Ember.Service is an Ember object that lives for the duration of the application, and can be made available in different parts of your application. Services are useful for features that require shared state or persistent connections.

您可以为您的组件使用一个参数。

{{fixed-header info=headerInfo}}
{{outlet}}

然后在任何路线中的某个钩子

setupController: function(controller, model) {
  this._super(controller, model);
  var headerInfo = ...
  this.controllerFor('application').set('headerInfo', headerInfo);
}