javascript - Split and group a collection of items in Ember -
i'm trying take collection of records in ember , split them groups of number, 2.
so example,
{{#each node in model}} <span>node.name</span> {{/each}}
i <span>thing</span><span>other thing</span><span>some thing</span><span>one more thing</span>
i want able pass node , wrap every 2 nodes div <div><span>thing</span><span>other thing</span></div><div><span>some thing</span><span>one more thing</span></div>
in ember 2.0 should component, best place handle logic. should component or controller?
given principle things related display, or preparations therefor, belong in component, prefer component. so:
partitions: computedpartition('model', 2)
then in template
{{#each partition in partitions}} <div> {{#each node in partition}} {{node.name}} {{/each}} </div> {{/each}}
now remains write computedpartition
, ember computed property:
function computedpartition(dependentkey, size) { return ember.computed(dependentkey + ".@each", function() { return partition(this.get(dependentkey), size); }); }
there different algorithms partitioning. see this question. here's short recursive one:
function partition(array, n) { array = array.slice(); return function _partition() { return array.length ? [array.splice(0, n)].concat(_partition()) : []; }(); }
going deeper
we can simplify (?) above introducing higher-level computed property called computedarrayinvoke
, invokes specified function on array-valued property specified key, along additional arguments:
function computedarrayinvoke(fn, dependentkey, ...args) { return ember.computed(dependentkey + ".@each", function() { return fn(this.get(dependentkey), ...args); }); }
now can write
partitions: computedarrayinvoke(partition, 'model', 2)
Comments
Post a Comment