Skip to content

Instantly share code, notes, and snippets.

@cbroeren
Created October 4, 2016 13:51
Show Gist options
  • Select an option

  • Save cbroeren/7a933848bc1b1c35887125e1936e99c1 to your computer and use it in GitHub Desktop.

Select an option

Save cbroeren/7a933848bc1b1c35887125e1936e99c1 to your computer and use it in GitHub Desktop.
New Twiddle
import Ember from 'ember';
import SelectionHandler from '../utils/selection';
export default Ember.Controller.extend({
content: [1, 2, 3, 4, 5],
init() {
this._super(...arguments);
this.set('selectionHandler', SelectionHandler.create());
Ember.bind(this, 'selectionHandler.content', 'content');
},
actions: {
selectItem(item) {
this.get('selectionHandler').select(item);
},
removeItem(item) {
let content = this.get('content');
this.set('content', content.removeObject(item));
}
}
});
<h2>Click to (de)select</h2>
<br>
Content: {{content.length}}
{{#each content as |item|}}
<div>
<span {{action "selectItem" item}}>Item {{item}}</span>
<button {{action "removeItem" item}}>X</button>
</div>
{{/each}}
<br>
Selection content: {{selectionHandler.content.length}}<br>
Selection selected: {{selectionHandler.selection.length}}
{{#each selectionHandler.selection as |item|}}
<div>Item {{item}}</div>
{{/each}}
{
"version": "0.10.5",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.8.0",
"ember-data": "2.8.0",
"ember-template-compiler": "2.8.0",
"ember-testing": "2.8.0"
},
"addons": {}
}
import Ember from 'ember';
import get from 'ember-metal/get';
import set from 'ember-metal/set';
import computed from 'ember-computed';
export default Ember.Object.extend({
content: null,
_selection: null,
selection: computed('_selection.[]', 'content.[]', function() {
let content = get(this, 'content');
let selection = get(this, '_selection');
if (!selection || !content) {
return Ember.A();
}
return content.filter((item) => {
return selection.indexOf(item) !== -1;
});
}),
init() {
this._super(...arguments);
set(this, 'content', Ember.A());
set(this, '_selection', Ember.A());
},
setContent(list) {
if (list && get(list, 'length')) {
set(this, 'content', list);
}
},
select(item) {
let selection = get(this, '_selection');
if (selection.includes(item)) {
selection.removeObject(item);
} else {
selection.pushObject(item);
}
},
isSelected(item) {
return get(this, 'selection').includes(item);
},
selectAll() {
set(this, '_selection', get(this, 'content'));
},
clear() {
set(this, '_selection', Ember.A());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment