我正在尝试在 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 中,几乎所有东西都应该是一个组件,哪里是处理这个逻辑的最佳位置。它应该是组件还是 Controller ?
最佳答案
考虑到与显示相关的东西或与之相关的准备工作都属于组件的原则,我更喜欢组件。你可以这样做:
partitions: computedPartition('model', 2)
然后在您的模板中
{{#each partition in partitions}}
<div>
{{#each node in partition}}
{{node.name}}
{{/each}}
</div>
{{/each}}
现在需要编写 compulatedPartition
,它是一个 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()) : [];
}();
}
更深入
我们可以通过引入一个名为compulatedArrayInvoke的更高级别的计算属性来简化(?)上述内容,该属性使用指定的键以及其他参数调用数组值属性上的指定函数:
function computedArrayInvoke(fn, dependentKey, ...args) {
return Ember.computed(dependentKey + ".@each", function() {
return fn(this.get(dependentKey), ...args);
});
}
现在我们可以写
partitions: computedArrayInvoke(partition, 'model', 2)
关于javascript - 在 Ember 中对项目集合进行拆分和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29641274/