我正试图在Ember中收集一些记录并将它们分成若干组,例如2。
例如,像
这样的东西{{#each node in model}}
<span>node.name</span>
{{/each}}
我得到<span>thing</span><span>other thing</span><span>some thing</span><span>one more thing</span>
我希望能够将节点传递给某个东西并用div包装每2个节点
像<div><span>thing</span><span>other thing</span></div><div><span>some thing</span><span>one more thing</span></div>
在Ember 2.0中,大多数应该是一个组件,哪里是处理这种逻辑的最佳位置。它应该是一个组件还是控制器?
答案 0 :(得分:4)
鉴于与显示或其准备相关的事物属于组件的原则,我更喜欢该组件。你可以这样做:
partitions: computedPartition('model', 2)
然后在你的模板中
{{#each partition in partitions}}
<div>
{{#each node in partition}}
{{node.name}}
{{/each}}
</div>
{{/each}}
现在仍然要写computedPartition
,这是一个Ember计算属性:
function computedPartition(dependentKey, size) {
return Ember.computed(dependentKey + ".@each", function() {
return partition(this.get(dependentKey), size);
});
}
分区有不同的算法。见this question。这是一个简短的递归:
function partition(array, n) {
array = array.slice();
return function _partition() {
return array.length ? [array.splice(0, n)].concat(_partition()) : [];
}();
}
我们可以通过引入一个名为computedArrayInvoke
的更高级别的计算属性来简化(?)上述内容,该属性使用指定的密钥调用数组值属性上的指定函数,以及其他参数:
function computedArrayInvoke(fn, dependentKey, ...args) {
return Ember.computed(dependentKey + ".@each", function() {
return fn(this.get(dependentKey), ...args);
});
}
现在我们可以写
partitions: computedArrayInvoke(partition, 'model', 2)