mma
mma

Reputation: 11

How can sibling components to talk to each other in Ember.js?

I want sibling Ember.js components to talk to each other so that, for example, only one component would be in an active state at any given time.

Upvotes: 0

Views: 660

Answers (1)

user663031
user663031

Reputation:

One useful pattern for handling this is to introduce an attribute on the invoking controller or component which remembers which child component is active, pass that to the component, and then check in the component to see if that attribute is itself:

PARENT CONTROLLER AND TEMPLATE

// thing/controller.js

// Remember which item is active.
// This will be changed by changeActive action, and passed to components.
activeItem: null,

actions: {
  // Change active item. Passed to component as handler for 'action'.
  changeActive(item) { this.set('activeItem', item); }
}
{{! thing/template.js }}

{{#each items as |item|}}
  {{item-component item=item active=activeItem action='changeActive'}}
{{/each}}

INDIVIDUAL ITEM COMPONENT LOGIC AND TEMPLATE

// components/item-component/component.js

// Give this component a disabled class if not the active item.
classNameBindings: ['isMe'::disabled'],

// Current active item--passed as attribute.
active: null,

// Check is I am the active item.
isMe: Ember.computed('active', function() { 
  return this === this.get('active'); 
}),

// Advise upstream that I have become active.
actions: {
  select() { this.sendAction('action', this); }
}
{{! components/item-component/template.js }}

Hello, I am item {{item.name}}. 
<span {{action 'select'}} Select me.</span>

Upvotes: 1

Related Questions