【发布时间】:2016-12-03 21:51:47
【问题描述】:
我正在尝试根据其中一个相关模型对一组模型对象进行排序。
我有一个 Document hasMany LineItem 和一个 LineItem belongsTo 位置。我想按位置对行项目进行排序。所以如果我有这样的事情:
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 并发等待所有关系加载完毕后再对数据进行排序。
这是我的控制器:
~/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,不正确。在初始化时,第一个任务运行,但不等待为每个行项目加载位置。我试图让它加载第二个任务中的所有位置,但显然不是正确的方法。因此在初始化时它将运行排序,但 _.groupBy 的函数将返回未定义,因为此时位置未定义。然后,如果我在知道位置已加载(因为我在模板的其他地方使用它们)之后再次手动运行任务(使用模板上的按钮),它工作正常。
解决方案不必使用 ember 并发,它只是看起来是正确的工具,但我认为它也可以使用 Promise 来完成。
【问题讨论】:
-
这不是“排序”。
标签: javascript ember.js ember-data