Mateus Vahl
Mateus Vahl

Reputation: 989

Ember communicate between view components and controllers

I have a dashboard and inside it some buttons for filter to posts.

This dashboard appear in all pages, so I a create a view dashboard with a template of same name.

to trigger filter, I have created an view 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');
  }
});

this action filter this sent to application controller, but I need send to an specific controller posts.index, hierarchically posts and dashboard have no connection. how can I create a communication correctly between my components?

Upvotes: 1

Views: 341

Answers (1)

To trigger an action from controller A to controller B, you need to have B in A's needs. Then you can do this.get('controllers.b').send('someAction').

Example code:

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

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

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

But as @sushant said, stop using controllers and views.

Use controllers and views for only top level on each route. E. g. any route will have one controller, one view and one template and (and you don't have to explicitly define them all).

For content nested in routes' templates, don't use controllers and views. Use components instead.

Upvotes: 1

Related Questions