Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I keep selection state for a list?

I'm using ember 1.0.0-pre4.

I want to display a list of Model instances. The user should be able to select as many list entries by clicking a button or checkbox that is rendered within each row.

I managed to display the list. But I don't know how to manage selection state. When I put something like {{view Ember.Checkbox checkedBinding="isSelected"}} into the template then the selection state will be held in my model. But I don't think this is the best place. I think selection state belongs to the controller or view state.

Could you please tell me the best way to store and access (multiple) list selection state?

like image 330
Marc Avatar asked Feb 07 '13 00:02

Marc


1 Answers

One way is to just keep a second list in the controller:

App.FooController = Ember.ArrayController.create({
  selectedContent: [],
  selectToggle: function(event) {
    var selectedContent;
    selectedContent = this.get(selectedContent);
    if (selectedContent.contains(event.context)) {
      return this.set('selectedContent', selectedContent.without(event.context));
    } else {
      return this.get('selectedContent').push(event.context);
    }
  }
});

<script type="text/x-handlebars" data-template-name="index">
  <ul>
    {{#each foo in controller}}
          <li {{action selectToggle foo}}>{{foo.name}}</li>
    {{/each}}
  </ul>
</script>

That just maintains a separate list in the controller and pushes/removes based on whether or not the item was selected.

You could also use an Ember.ObjectProxy to augment the values of the foo object with an "isSelected" property.

App.FooController = Ember.ArrayController.create({
  selectedContent: @get('content').map(function(item){
    Ember.ObjectProxy.create({ 
      content: item
      isSelected: false
    });
  }); 
});

<script type="text/x-handlebars" data-template-name="index">
  <ul>
    {{#each foo in controller.selectedContent}}
          <li {{bindAttr class= "foo.isSelected"}}{{action selectToggle foo}}>{{foo.name}}</li>
    {{/each}}
  </ul>
</script>

Then in your selectToggle method you just set foo's isSelected property appropriately.

like image 176
Andre Malan Avatar answered Sep 29 '22 11:09

Andre Malan