Ember 在视图组件和控制器之间进行通信

Ember communicate between view components and controllers

我有一个仪表板,里面有一些用于过滤 posts 的按钮。

此仪表板出现在所有页面中,因此我使用同名模板创建了一个视图dashboard

为了触发过滤器,我创建了一个视图 filter-button:

export default Ember.View.extend(Ember.TargetActionSupport, {
  tagName: 'button',
  click(event) {
    this._toggleComponentState();
    this._dispatchAction();
  },
  _dispatchAction() {
    this.triggerAction({
      action: "filter",
      target: this.get('controller'),
      actionContext: this.get('context')
    });
  },
  _toggleComponentState() {
    this.$().toggleClass('active');
  }
});

此操作 filter 此已发送至 application controller,但我需要发送至特定控制器 posts.index,分层帖子和仪表板没有连接。如何在我的组件之间正确创建通信?

要触发从控制器 A 到控制器 B 的操作,您需要在 A 的 needs 中包含 B。然后你可以做 this.get('controllers.b').send('someAction').

示例代码:

App.IndexController = Ember.Controller.extend({
  needs: ['foo'],

  actions: {
    lolAction: function() {
      var fooCtrl = this.get('controllers.foo');
      fooCtrl.send('anotherLolAction');
    }
  }
});

演示:http://emberjs.jsbin.com/tevagu/1/edit?html,js,output

但正如@sushant 所说,停止使用控制器和视图。

仅在每条路线的顶层使用控制器和视图。例如任何路由都将有一个控制器、一个视图和一个模板,并且(您不必显式定义它们)。

对于嵌套在路由模板中的内容,不要使用控制器和视图。请改用组件。