1

主要目标:用于访问当前控制器中可用的模型.find()以外的模型 - 以便将来自当前控制器模型的数据与来自“外国”控制器模型的数据进行比较。

触发比较的原因: 我在模板中有一个按钮,带有{{ action "isResponse"}}. 这个模板的控制器有一个isResponse : function() {...}

我遇到的问题:每次单击按钮时都会触发该操作,但App.Answer.find()仅在第二次单击后才返回内容。我想知道这是否是因为Answer模型尚未加载,但我不确定如何在我的示例中正确设置观察者isLoaded(如果这甚至是问题)

那么 App.Answer.find() 第一次调用时怎么会返回空呢?

App.ChoiceController = Ember.ObjectController.extend({

    chosen: false,

    isResponse: function() {

        // successfully returns what I want from this controller's model
        var questionId = this.get('question.id')

        // gets DS.RecordArray of the model i'd like to compare with
        var answers = App.Answer.find()

        // filter to get a result that matches this.get('question.id')
        var answer = answers.filter(function(ans) {

            // returns all entries that match
            if(ans.get('question.id') == questionId) { return true }

        }, 'answers.isLoaded'); // this observer doesn't seem to hurt or help

        // get the final value I need 
        var choice = answer.mapProperty('choice.id')

        // if choice array is not empty, (should only have 1 element anyways)
        if(!choice) {
            this.set('chosen', choice[0]);

        } else {

            this.set('chosen', false);
        }
    }

})

以下是涉及的模型。两者都包含 DS.belongsTo 属性

App.Choice = DS.Model.extend({

    "question" : DS.belongsTo('App.Question')

})

App.Answer = DS.Model.extend({

    "question" : DS.belongsTo('App.Question')
    "choice" : DS.belongsTo('App.Choice')    

})

App.Question = DS.Model.extend({

})

编辑

这是显示行为的jsfiddle。确保打开浏览器控制台,注意每个按钮都需要单击 2 次isResponse才能正常运行。http://jsfiddle.net/iceking1624/QMBwe/

4

1 回答 1

1

在阅读了您的评论后,我重新设计了一个解决您的问题的方法,一种可能的方法可能是您可以定义一个AnswerControllerof 类型ArrayController(因为它是一个答案的集合),然后在您ApplicationRoutesetupController钩子中设置这个控制器。

主要目标:使用 .find() 访问当前控制器中可用的模型以外的模型 - 以便将来自当前控制器模型的数据与来自“外国”控制器模型的数据进行比较。

稍后,您可以从需要访问答案集合的任何控制器内部AnswerController使用needsAPI要求访问 的数据needs:['answers'],最后可以使用 访问数据this.get('controllers.answer')。您可以在此处needs找到有关API的更多信息。

请参阅此处的一个可能的解决方案,该解决方案可以正常工作,并在点击时显示正确的选择1st

App.AnswerController = Ember.ArrayController.extend({});

App.ApplicationRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    this.controllerFor('answer').set('content', App.Answer.find());
  }
});

App.ChoiceController = Ember.ObjectController.extend({
  needs: ['answer'],
  chosen: false,
  isResponse: function() {

    var questionId = this.get('question.id');

    var answers = this.get('controllers.answer');

    var answer = answers.content.filter(function(ans) {
      if(ans.get('question.id') == questionId) { return true }
    }

    var choice = answer.mapProperty('choice.id');

    if(!choice) {
      this.set('chosen', choice[0]);
    } else {
      this.set('chosen', false);
    }
  }
});

这里有一个工作小提琴

希望能帮助到你。

于 2013-06-15T10:20:47.280 回答