【发布时间】:2014-11-05 19:32:37
【问题描述】:
我是 ember 开发的新手,在处理此类任务时需要帮助:
目前我正在使用 ember-cli 应用程序中的 Fixtures。 涉及的两个模型是:
var Recipe = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
ingredients: DS.hasMany('ingredients',{async: true}),
recipeCategory: DS.belongsTo('recipeCategory', {async: true})
});
var Ingredient = DS.Model.extend({
title: DS.attr('string'),
portion: DS.attr('string'),
groupTag: DS.attr('string'),
recipe: DS.belongsTo('recipe')
});
虽然列出通过嵌套路由调用的特定配方的所有成分(也已排序)没有问题,
this.resource('recipes',function(){
this.resource('recipe', {path: '/:recipe_id'});
});
我在按 groupTag 对成分进行分组时遇到了大问题。分组的逻辑不是问题,但我要么在访问控制器中的模型以获取计算属性时遇到竞争条件,要么在尝试处理模板中的 Promise 时遇到框架错误。
以下是相关模板:
//recipe.hbs
<strong>{{recipeCategory.title}}</strong>
<h3>{{title}}</h3>
{{render 'ingredients' ingredients}}
//ingredients.hbs
<strong>Zutaten</strong>
<ul>
{{#each groupedIngredients}}
<li>{{group}}
<ul>
{{#each items}}
<li>{{portion}} {{title}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
我的成分控制器如下所示:
var IngredientsController = Ember.ArrayController.extend({
sortProperties: ['title'],
sortedIngredients: Ember.computed.sort('model', 'sortProperties'),
groupedIngredients: function(){
return this.get('model').then(function(ingredients){
var groupTags = ingredients.mapBy('groupTag').uniq();
var groupedIngredients = groupTags.map(function(gtag){
return {
group: gtag,
items: ingredients.map(function(item){
if ( item.get('groupTag') == gtag){
return item;
}
}).compact()
};
});
console.log(groupedIngredients);
return groupedIngredients;
});
}.property('model')
});
promise 里面的控制台日志没问题,但是我无法返回给模板进行评估的promise:
Uncaught Error: Assertion Failed: The value that #each loops over must be an Array. You passed {_id: 158, _label: undefined, _state: undefined, _result: undefined, _subscribers: }
当我删除承诺并只处理 this.get('model') 时,计算的数组中充满了未定义的值,导致模型似乎没有完全加载。 如何解决此问题以以这种方式处理异步模型数据? 谢谢!
【问题讨论】:
标签: javascript ember.js controller