使用emberjs / handlebars显示表格中的倍数

时间:2014-04-08 08:06:57

标签: ember.js handlebars.js

我正在开发一个基于ember的个人项目,我对我想要实现的东西感到困惑:

我需要能够显示一个表(基于ArrayController的模型),在这个表中我需要显示一个列,汇总所有前一行中另一列的所有值。

我知道如何将所有行合并为一个值,但我不知道如何为每一行执行此操作。

这是我需要实现的目标:

__________________________
   value    |     sum
__________________________
     1      |      1
__________________________
     2      |      3
__________________________
    -1      |      2

依旧......

“value”是我的ArrayController模型中每个DS.Model的字段。

我不是在寻找最终的实施,而是一些关于如何实现这一目标的提示。

感谢您阅读,

皮尔。

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

(JavaScript的)

App = Ember.Application.create();

App.Router.map(function() {
});

App.IndexController = Ember.Controller.extend({
  actions: {
    inc: function () {
      this.get("model")[1].incrementProperty("val");
    }
  }
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    var a = App.Model.create({
      val: 1
    });
    var b = App.Model.create({
      val: 2,
      prev: a
    });
    var c = App.Model.create({
      val: -1,
      prev: b
    });
    return [a, b, c];
  }
});

App.Model = Ember.Object.extend({
  val: 0,
  prev: null,
  sum: function () {
    var val = this.get("val"),
        prev = this.get("prev");
    if (!prev) {
      return val;
    }
    return prev.get("sum") + val;
  }.property("val", "prev.sum")
});

(模板)

<script type="text/x-handlebars" data-template-name="index">
    <ul>
    {{#each item in model}}
      <li>{{item.val}} | {{item.sum}}</li>
    {{/each}}
    </ul>
    <button type="button" {{action inc}}>Inc</button>
  </script>

工作示例here

唯一需要注意的是,您必须创建和维护元素之间的链接。如果您重新调整数组,添加新元素等...您必须手动重新创建所有引用。


<强>更新

我对这个问题很感兴趣,所以我又给了它。

App.IndexRoute = Ember.Route.extend({
  model: function() {
    var col = [];
    col.push(App.Model.create({
      val: 1,
      all: col
    }));
    col.push(App.Model.create({
      val: 2,
      all: col
    }));
    col.push(App.Model.create({
      val: -1,
      all: col
    }));
    return col;
  }
});

App.Model = Ember.Object.extend({
  val: 0,
  all: null,
  prev: function () {
    var all = this.get("all");
    for (var i = 0; i < all.length - 1; i++) {
      if (all[i + 1] === this) {
        return all[i];
      }
    }
    return null;
  }.property("all.[]"),
  sum: function () {
    var val = this.get("val"),
        prev = this.get("prev");
    if (!prev) {
      return val;
    }
    return prev.get("sum") + val;
  }.property("val", "prev.sum")
});

更新的直播演示为here

这将跟踪父集合中的更改并自动确定previous元素。