Search code examples
ember.jshandlebars.jsember-components

How do independent components communicate in ember?


How do I let independent component let know of changes or events in a component?

eg:

 <#user-social profile>
  {{partial 'user-handle'}}

  <div class='subtext'> 
    {{#reply-component}} {{/reply-component}}
  </div>

  <div class='replybox hide'>
    <textarea></textarea>
    <input type='button' value='Reply to user' />
  </div>
 </user-social profile>

Problem: I want replybox to toggle its visibility when a link inside reply component is clicked.


Solution

  • Components are isolated by design. It’s your responsibility to specify their dependencies. You can introduce communication channels between a parent and child component either by passing bound attributes to the child or specifying actions for the child to trigger on the parent.

    Actions are probably a better fit, as using two-way bindings as a form of communication is increasingly considered an anti-pattern. An example:

    {{#reply-component toggleReplybox="toggleReplybox"}}
    

    Then, in your child component:

    actions: {
      whateverTriggersTheToggle: function() {
        this.sendAction('toggleReplybox');
      }
    }
    

    You’d have to add the whateverTriggersTheToggle action to something inside the child component.

    In the parent component: displayReplybox: false,

    actions: {
      toggleReplybox: function() {
        this.set('displayReplybox', !this.get('displayReplybox'));
      }
    }
    

    This would necessitate adding an {{#if displayReplybox}} wrapper around your replybox element.