拆分和分组 Ember 中的项目集合

Split and group a collection of items in Ember

我正在尝试收集 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 中,大多数东西都应该是组件,这是处理此逻辑的最佳位置。应该是组件还是控制器?

按照展示相关的东西,或者展示的准备都属于组件的原则,我更倾向于组件。你可以这样做:

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)