Search code examples
ember.jshandlebars.js

Applying background color to component in ember js


I have a toolbar component which has a list of items. When I click on an element I need to add background color to the clicked element. Also need to deselect the previously selected item.

I tried using classNameBinding but it applies to all the elements in the list.

How can I apply Background Color to the elements which are clicked inside the Component

In Template:

<script type="text/x-handlebars" data-template-name="components/test-toolbar">
  <ul>
     <li {{bindAttr class="bgColor"}} {{action 'redClick'}}> 
      Red
     </li>
     <li {{bindAttr class="bgColor"}}>
      Yellow
     </li>
     <li {{bindAttr class="bgColor"}}>
      Blue
     </li>
  </ul>
</script>


<script type="text/x-handlebars" data-template-name="index">
  <div>
    {{test-toolbar}}
  </div>
</script>

In app.js:

App.TestToolbarComponent = Ember.Component.extend({
  classNameBindings: ['bgColor'],
  bgColor: false,

  actions: {
    redClick: function () {
       this.set('bgColor', true);
    }
  }
});

Here is the working DEMO: JSBIN LINK


Solution

  • Using actions you can't get the target element to manipulate it. Also using 3 different actions for same is something i don't suggest. You can use click hook to handle this in simple jquery way. here is code and jsbin link

    App.TestToolbarComponent = Ember.Component.extend({
      click: function(event){
        var elem = Ember.$(event.target);
        if(elem.is('li')) {
          this.$('li').removeClass('active');
          elem.addClass('active');
        }
      }
    });
    

    http://emberjs.jsbin.com/qiriwi/2/edit