javascript - 在 Ember 中对项目集合进行拆分和分组

标签 javascript ember.js ember-cli

我正在尝试在 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/

相关文章:

javascript - Angular 5 错误 :Can't bind to 'ngForFor' since it isn't a known property of 'li'

javascript - 为什么调用 jQuery 的 appendChild 会因未定义错误而失败?

javascript - createRecord 将空 req.body 发送到我的 express.js 服务器后,Ember.js save()

ember.js - 转到新路线时未删除 Emberjs 模板

javascript - 遍历对象数组的嵌套子对象并使属性等于 false - JavaScript

forms - Emberjs easyForm 选择设置值

ember.js - 如何将数据从路由发送到组件?

javascript - Ember.js 2、transitionTo 在一级路由中使用多个动态段

javascript - 按钮上的禁用似乎没有生效

javascript - TinyMCE 删除 "format"下拉