1

使用 Ember-Data 0.13-59 和 Ember 1.0.0 RC 6(来自入门套件)

问题:save()App.Userstat.createRecord({ ... })服务器生成的新记录获取并POST成功返回一个但新记录在模型id中不可用。Userstat

为了更好地理解示例:这是一个测验应用程序(用于多项选择题)。每个问题都有几个选项,当用户选择一个选项时,他们对相应问题的选择存储在一个模型中,App.Userstat.

对于每个问题,应用程序都需要知道用户是否已经回答了这个问题,或者它是否是新问题。

我将计算属性用作 asettergetter。当setter用户选择一个选项时调用 (选项的值被传递给计算属性)。首先,它检查用户当前问题的记录是否存在。如果它不存在,它将创建一个新记录。如果确实存在,它应该只发出PUT更新内容的请求。

代码更新(7 月 8 日上午 11 点)

App.UserstatsController = Ember.ArrayController.extend();

App.QuestionController = Ember.ObjectController.extend({
  needs: "userstats",

  chosen = function(key, value) {
    // getter
    if(value === undefined) {

       // something goes here

    // setter
    } else {

      // the question.id is used to compare for an existing record in Userstat mdoel
      var questionId = this.get('id');
      var questionModel = this.get('model');

      // does any Userstat record belong to the current question??
      var stats = this.get('controllers.Userstats');
      var stat = stats.get('model').findProperty('question.id', questionId);

      // if no record exists for stat, means user has not answered this question yet...
      if(!stat) {

        newStat = App.Userstat.createRecord({
          "question" : questionModel,
          "choice" : value       // value passed to the computed property
        )}

        newStat.save();                     // I've tried this
        // newStat.get('store').commit();   // and this
        return value;

      // if there is a record(stat) then we will just update the user's choice
      } else {
        stat.set('choice', value);
        stat.get('store').commit();
        return value;
    }
  }.property('controllers.Userstats')

无论我设置多少次,chosen它总是发送一个POST(而不是只发送一个 PUT 请求的更新),因为它从来没有第一次将记录添加到模型中。

为了进一步演示,在setter计算属性的部分,当我输入这段代码时:

var stats = this.get('controllers.Userstats')
console.log stats 

Userstats 控制器显示所有以前存在的记录,但不显示新提交的记录!

怎么新的记录在我save()或者commit()它之后就没有了???

谢谢 :)

编辑

也许这与我向奇异模型中添加记录有关App.Userstat,然后当我查找它时,我正在使用作为数组控制器的 UserstatsController 进行搜索???

4

1 回答 1

1

我不知道这是否是一个错字,但计算属性的定义方式错误,应该是这样的:

App.QuestionController = Ember.ObjectController.extend({
  needs: 'userstats',
  choice: 'controllers.userstats.choice',
  chosen: function(key, value) {
    ...
  }.property('choice')
  ...
});

在内部,property()您还应该定义在发生更改时触发计算属性的属性。这样,如果choice更改chosen将触发 cp。

如果有帮助,请告诉我。

于 2013-07-08T07:56:55.110 回答