主要目标:使用.find()
访问当前 Controller 中可用的模型之外的模型 - 以便将当前 Controller 模型中的数据与来自“外国” Controller 模型的一段数据。
触发比较的因素:
我的模板内有一个带有 {{ action "isResponse"}}
的按钮。该模板的 Controller 有一个 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/
最佳答案
阅读完您的评论后,我重新考虑了您的问题的解决方案,一种可能的方法可能是您可以定义 ArrayController
类型的 AnswerController
(因为它是针对答案集合),然后在 ApplicationRoute
的 setupController
Hook 中设置此 Controller 。
Main goal: Using .find() to access a model other than the one available in the current controller -in order to compare data from the current controller's model with a piece of data from a 'foreign' controller's model.
稍后,您可以使用 needs
API 和 needs:['answers']
请求访问 AnswerController
的数据在需要访问答案集合的任何 Controller 内,最后可以使用 this.get('controllers.answer')
访问数据。您可以找到here有关needs
API 的更多信息。
在这里查看一个可能正确工作的解决方案,在第一次
点击时显示正确的选择:
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);
}
}
});
这是一个正在运行的fiddle .
希望有帮助。
关于javascript - ember.js .find() 仅在第二次调用时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17119547/