Question

I have an each loop in my template that iterates over the tiles to the page.

Within each tile I have a button initially set to show the text "select me" within the button.

When the button is clicked I simply want to be able to set a property named 'selected' to the tiles object and set it to true when the action button is clicked so that the text on the button changes to "unselect me".

Only one of the tiles can have selected: true at any given time. The others can be to false.

App = Ember.Application.create();

//Items
App.IndexRoute = Ember.Route.extend({
    model: function() {
        return tiles;
    }
});

App.IndexView = Ember.View.extend({

    actions: {
        productClick: function(id){

            var tile = tiles.findBy('id', id);

            tile.set('selected', true);
        }
    }
});

var tiles = [
    {
        id: '1',
        title: 'tile 1'
    },
    {
        id: '2',
        title: 'tile 2'
    },
    {
        id: '3',
        title: 'tile 3'
    }
];

templates:

  <!--Index page-->
  <script type="text/x-handlebars">
    <div class="tile-wrapper">
      <div class="page-header">
        <h1>Test</h1>
      </div>

      {{outlet}}
    </div>
  </script>

  <!--Tiles-->
  <script type="text/x-handlebars" id="index">
    <div class="row">
      {{#each}}
        {{partial 'tile'}}
      {{/each}}
    </div>

    {{outlet}}
  </script>

  <!--Tile partial-->
  <script type="text/x-handlebars" id="_tile">
    <div class="col-md-3">
      <div class="thumbnail">
        <p>{{title}}</p>


        <button {{action "productClick" id target="view"}}>
          {{#if selected}}
            unselect me
          {{else}}
            select me
          {{/if}}
        </button>


      </div>
    </div>
  </script>
Était-ce utile?

La solution

You can save the state of the selected item and create a computed property in your view component which compares if the view content is selected or not.

App.IndexController = Em.ArrayController.extend({
  selected: null,
  actions: {
     productClick: function(title){
       this.set('selected', title);
     }
  }

});

App.SelectButtonComponent = Em.Component.extend({

  isSelected: Em.computed(function() {
    return this.get('content') === this.get('selected');
  }).property('content', 'selected'),

  click: function() {

    this.sendAction('action', this.get('content'));

  }
});


  <script type="text/x-handlebars" data-template-name="components/select-button">
          {{#if isSelected}}
            unselect me 
          {{else}}
            select me
          {{/if}}
  </script>

  {{select-button tagName='button' action="productClick"
    content=item  selected=selected}}

http://emberjs.jsbin.com/zicib/1/edit

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top