如何返回在Ajax请求上创建的计算属性(hasMany关系)

时间:2014-02-14 19:28:59

标签: ember.js ember-data

我正在尝试在我的模型中创建一个计算属性,但由于在使用get时调用了Ajax请求,我无法返回值(我想计算任务的百分比)完成并分配给该项目)

模型

Docket.Project = DS.Model.extend({
  name:        DS.attr('string'),
  description: DS.attr('string'),
  number:      DS.attr('string'),
  archived:    DS.attr('boolean'),
  customer:    DS.belongsTo('customer'),
  tasks:       DS.hasMany('task',{ async: true }),

  // custom attributes
  progress: function() {

    var done = 0,
        progress = 0;

    this.get('tasks').then(function(tasks) {
      tasks.forEach(function(task) {
        if (task.get('status') == 5) done++
      });

      progress = (done / tasks.get('length')) * 100;

    });

    console.log(progress);

    return progress;

  }.property('tasks')
});

模板

<span class="progress"><span class="bar"></span>{{progress}}%</span>

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

您需要向观察者添加@each。试试这个:

progress: function() {
    var done = 0,
        progress = 0;

    this.get('tasks').forEach(function(task) {
        if (task.get('status') == 5) done++;
    });

    progress = (done / tasks.get('length')) * 100;

    console.log(progress);
    return progress;
  }.property('tasks.@each.status')