我试图根据其相关模型之一对模型对象的数组进行排序。Ember等待关系加载与阵列与烬并发
我有一个文档这的hasMany的LineItem和的LineItem属于关联一个位置。我想根据其位置对行项目进行排序。所以,如果我有这样的事情:
let lineItems = [
{
itemName: "One",
location: {
name: "Kitchen"
}
},
{
itemName: "Two",
location: {
name: "Kitchen"
}
},
{
itemName: "Three",
location: {
name: "Bathroom"
}
},
{
itemName: "Four",
location: {
name: "Bathroom"
}
},
{
itemName: "Five",
location: {
name: "Hall"
}
},
{
itemName: "Six",
location: {
name: "Hall"
}
}
];
我愿意去:
let groupedLineItems = {
"Kitchen": [
{
itemName: "One",
location: "Kitchen"
},
{
itemName: "Two",
location: "Kitchen"
},
],
"Bathroom": [
{
itemName: "Three",
location: "Bathroom"
},
{
itemName: "Four",
location: "Bathroom"
},
],
"Hall": [
{
itemName: "Five",
location: "Hall"
},
{
itemName: "Six",
location: "Hall"
}
]
}
我已经想通了如何排序,但只有一次,所有的关系都加载。我无法弄清楚如何在排序数据之前使用ember concurrency来等待所有关系加载。
这是我的控制器:
~/app/controllers/document.js
import Ember from 'ember';
import _ from 'underscore';
import { task } from 'ember-concurrency';
const { computed } = Ember;
export default Ember.Controller.extend({
init() {
this.get('myTask').perform();
},
myTask: task(function *() {
// Wait for locations to resolve.
let lineItems = this.get('model').get('lineItems');
yield this.get("secondTask").perform(lineItems);
let groupedLineItems = yield _.groupBy(lineItems.toArray(), (lineItem) => {
lineItem.get('location').then((location) => {
return location.get('name');
});
});
this.set("groupedLineItems2", Ember.Object.create(groupedLineItems));
}),
secondTask: task(function * (lineItems) {
yield lineItems.toArray().forEach((lineItem) => {
lineItem.get('location');
});
})
});
这是WIP控制器上,而不是正确的。在init中,第一个任务运行,但不会等待每个行项目的位置加载。我试图让它加载第二个任务中的所有位置,但显然不是正确的方法。因此,在init中,它将通过排序来运行,但_.groupBy的函数将返回undefined,因为该位置的位置未定义。然后,如果我知道位置已加载后(因为我在模板的其他地方使用它们)手动再次手动执行任务(使用模板上的按钮),它可以正常工作。
解决方案不必使用ember并发性,它看起来像是正确的工具,但我认为它也可以用promise来完成。
这不是“排序”。 – 2016-12-04 05:41:24