说我有这样的关系:
App.Library = DS.Model.extend
authors = DS.hasMany(App.Author, {async: true})
App.Author = DS.Model.extend
books: DS.hasMany(App.Book, {async: true)
App.Book = DS.Model.extend()
我希望从我图书馆的所有作者那里获得所有书籍。如果不是Promises
当两个关系都是异步时,我该怎么做。
以下是我的想法
allBooks: Ember.computed('authors', function() {
var r = []
this.get('authors').then(function(authors) {
authors.forEach(function(author) {
author.get('books').then(function(books) {
books.forEach(function(book){
r.push.apply(r, book);
});
});
});
});
return r;
}
更新:
我之前应该说过,但实际上我确实使用了以下代码。但是现在不推荐使用ArrayController,我正在寻找其他方法来实现同样的结果。
allBooks: Ember.computed('authors', function() {
var allBooks = Ember.ArrayController.create();
this.get('authors').then(function(authors) {
authors.forEach(function(author) {
author.get('books').then(function(books) {
books.forEach(function(book){
allBooks.addObject(book);
});
});
});
});
return allBooks;
}
我想我可以做这样的事情还有另外一种更好的方式吗?:
books: Ember.computed('authors', function() {
var a = Ember.Object.create({
content: Ember.A()
});
this.get('authors').then(function(authors) {
authors.forEach(function(author) {
author.get('books').then(function(books) {
books.forEach(function(book){
a.get('content').addObject(book);
});
});
});
});
return a.get('content');
}),
答案 0 :(得分:1)
您可以在路线中组装阵列,使用控制器中的PromiseProxyMixin(或者如果您不希望它们作为主模型,则使用连接到控制器的其他对象。)
// in route
setupController: function(controller, model) {
var allBooksPromise = new Ember.RSVP.Promise(function (resolve, reject) {
// get your books here
var allBooks = ...
resolve(allBooks);
}
controller.set('promise', allBooksPromise);
}
// in controller
export default Ember.Controller.extend(Ember.PromiseProxyMixin);
// in template
{{#if controller.isPending}}
Getting all of the books...
{{else}}
<ul>
{{#each controller.content as |book|}}
<li>{{book.title}}</li>
{{/each}}
</ul>
{{/if}}