Skip to content

Instantly share code, notes, and snippets.

@luxzeitlos
Created October 15, 2018 22:23
Show Gist options
  • Save luxzeitlos/f7965319bd2e061c5f6bab2a94807dda to your computer and use it in GitHub Desktop.
Save luxzeitlos/f7965319bd2e061c5f6bab2a94807dda to your computer and use it in GitHub Desktop.
New Twiddle
import Ember from 'ember';
export default Ember.Component.extend({
selected: [],
actions: {
select(id) {
// this is a *bit* ugly because the child object has no relation to the parent. So there is actually not a *easy* way to get the right parent or to know if its a child or a parent.
// so this code basically gives us the array of elements that are valid selections.
// if the clicked element is a parent thats all parents (so this.data)
// if the clicked element is a child thats all children of the parent
const group = this.data.find(x => x.id === id)
? this.data
: this.data.find(p => p.children.find(c => c.id === id)).children;
const validIds = group.map(x => x.id);
this.set('selected', [
id,
...this.selected.filter(s => validIds.includes(s)),
]);
}
}
});
import Ember from 'ember';
export function includes([elem, arr]/*, hash*/) {
return arr.includes(elem);
}
export default Ember.Helper.helper(includes);
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return [{
id: 1,
label: 'burger',
children: [{
id: 3,
label: 'tomato',
}, {
id: 4,
label: 'lettus',
}, {
id: 5,
label: 'pickle',
}]
}, {
id: 2,
label: 'kebab',
children: [{
id: 6,
label: 'ketchup',
}, {
id: 7,
label: 'chilli',
}]
}, {
id: 8,
label: 'coffee maker',
children: [{
id: 9,
label: 'filter',
}, {
id: 10,
label: 'grounds',
}]
}];
}
});
{{my-component data=model}}
Selected: {{selected}}
<ul>
{{#each data as |item|}}
<li>
<input
type="checkbox"
checked={{includes item.id selected}}
onclick={{action 'select' item.id}}
>
{{item.id}} {{item.label}}
<ul>
{{#each item.children as |child|}}
<li>
<input
type="checkbox"
checked={{includes child.id selected}}
onclick={{action 'select' child.id}}
>
{{child.id}} {{child.label}}
</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
{
"version": "0.15.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "3.4.3",
"ember-template-compiler": "3.4.3",
"ember-testing": "3.4.3"
},
"addons": {
"ember-data": "3.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment