【问题标题】:Ember-data model computed value, return value instead of promiseEmber-data 模型计算值,返回值而不是 promise
【发布时间】:2013-09-21 01:07:06
【问题描述】:

我有名为 surveyquestionresponse 的 ember 模型。 surveys 有多个questions,它们有多个responses。每个response 都有一个属性count

如何在survey 模型中设置total_response_count 计算值?在 emberjs 1.0.0 中,questions 在 DS.PromiseArray 中(由于 async: true),所以当我返回计算值时,它在我的模板中显示为对象而不是值。

我可以从question 模型轻松访问responses,因为responses 嵌入在question 中。但是,Ember 会自动为 survey 引用的 questions 做出承诺,因为 {async: true}。

调查模型:

App.Survey = DS.Model.extend({
  title: DS.attr('string'),
  owner_id: DS.belongsTo('user'),
  questions: DS.hasMany('question', {async:true}),

  total_responses: function() {
    var question_cb = function(prevValue, item) {
      return prevValue + item.get('total_responses');
    };

    return this.get('questions').then(function(questions){
      return questions.reduce(question_cb, 0);
    });
  }.property('questions')
});

问题模型:

App.Question = DS.Model.extend({
  survey: DS.belongsTo('survey'),

  question: DS.attr('string'),

  responses: DS.hasMany('response'),

  total_responses: function() {
    var response_cb = function(prevValue, item) {
      return prevValue + item.get('count');
    };

    return this.get('responses').reduce(response_cb, 0);
  }.property('responses')
});

响应模型:

App.Response = DS.Model.extend({
  response: DS.attr('string'),
  count: DS.attr('number'),

  question: DS.belongsTo('question')
});

我正在使用 ember-1.0.0 和 ember-data 1.0 beta-2。

【问题讨论】:

  • 你可以尝试直接在this.get('questions')PromiseArray 上调用reduce 吗?
  • 我做到了;它不起作用,因为它试图直接减少 PromiseArray,并且由于它是一个“长度为 0 的数组”,它返回 0。
  • questionsquestions.isFulfilled 计算如何?
  • 我该怎么做?履行承诺时数据位于何处?我在检查元素中找不到它。
  • 您是否尝试过根据questions.@each 计算属性?

标签: ember.js ember-data promise


【解决方案1】:

我也在Github上问过这个问题,得到了Yehuda Katz的回复:

你可以试试这样的:

App.Survey = DS.Model.extend({
  title: DS.attr(),
  owner: DS.belongsTo('user'),
  questions: DS.hasMany({ async:true }),

  totalResponses: Ember.arrayComputed('questions', {
    initialValue: 0,
    addedItem: function(accum, item) {
      accum += item.get('totalResponses');
    },
    removedItem: function(accum, item) {
      accum -= item.get('totalResponses');
    }
  })
});

当问题解决时,totalResponses 中的 addedItem 回调将为已解决数组中的每个项目调用一次。

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2019-07-06
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2022-08-19
    • 2016-11-08
    相关资源
    最近更新 更多