问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/14741467/where-should-i-keep-selection-state-for-a-list