ember.jshtmlbars

Pass a reference of the clicked DOM element to the action handler in Ember


I have a set of buttons whose state I wish to toggle with a class active. If I had a single button, then I would bind the active class to a controller property and toggle that property in the click handler:

<button {{action 'toggle'}} class="{{active}}">model.title</button>

actions: {
  toggle: function() {
    this.set('active', true);
  }
}

But I have multiple buttons, so I am not sure what I can bind. It would be useful if I could pass a reference to the clicked button to the action handler, but I'm not sure how to do this.

{{#each item in model}}
  <button {{action 'toggle' referenceToButton}}>model.title</button>
{{/each}}

actions: {
  toggle: function(buttonReference) {
    // add `active` class to buttonReference
  }
}

What is the best way to accomplish this?


Solution

  • Isn't the model-item what you want to pass and not the button?

    Then your toggle can just set an attribute on the item which you bind to your button class.

    {{#each item in model}}
      <button {{bind-attr class="item.isActive:active"}} {{action 'toggle' item}}>model.title</button>
    {{/each}}
    
    actions: {
      toggle: function(item) {
        item.set('isActive', true);
      }
    }