Skip to content

Instantly share code, notes, and snippets.

@arenoir
Last active March 26, 2016 21:39
Show Gist options
  • Save arenoir/02774605f501cbc0522a to your computer and use it in GitHub Desktop.
Save arenoir/02774605f501cbc0522a to your computer and use it in GitHub Desktop.
Ember group by computed macro
import Ember from 'ember';
var get = Ember.get,
arrayComputed = Ember.arrayComputed;
export default function (dependentKey, property) {
var options = {
initialValue: [],
addedItem: function(array, item, changeMeta, instanceMeta) {
var key = get(item, property),
group = array.findBy('key', key);
if (!group) {
group = Ember.ArrayProxy.create({
content: [],
key: key
});
array.pushObject(group);
}
group.pushObject(item);
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
var key = get(item, property),
group = array.findBy('key', key);
if (!group) {
return;
}
group.removeObject(item);
if (get(group, 'length') === 0) {
array.removeObject(group);
}
return array;
}
};
return arrayComputed(dependentKey, options);
}
import Ember from 'ember';
import groupBy from '../utils/group-by';
export default Ember.ArrayController.extend({
itemController: 'item',
groupedContent: groupBy('@this', 'category')
});
{{#each groupedContent}}
<li>{{key}}</li>
<ul>
{{#each}}
<li>{{name}}</li>
{{/each}}
</ul>
{{/each}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment