我有一个处理模型列表的 Controller 。这些模型有两种不同的类型(例如 Message
和 Comment
)。为了使用 ArrayController 我必须将两个列表合并为一个。有办法做到这一点吗?
基于类的多态性,as proposed in this thread ,可以解决我的问题,但它们不太可能很快实现。
在我当前的解决方案中,我使用 ObjectController
接收评论
和消息
。然后我使用计算属性合并它们:
App.SomeRoute = Ember.Route.extend({
model: function (params) {
return Em.Object.create({
comments: this.store.find('comment'),
messages: this.store.find('message'),
});
},
});
App.SomeIndexController = Ember.ObjectController.extend({
merged: Em.computed.union('messages', 'comments'),
});
它可以工作,但我并没有受益于 ArrayController
的所有优点(例如 sortProperties
)。
我想做的是:
App.SomeRoute = Ember.Route.extend({
model: function (params) {
var comments = this.store.find('comment');
var messages = this.store.find('message');
return merge(comments, messages);
},
});
其中 merge
返回的内容与 this.store.find('model')
返回的内容类似。
最佳答案
我最近问了类似的问题,这是我解决这个问题的方法。
App.SomeIndexController = Ember.ObjectController.extend({
sortProperties: ['some field'],
sortAscending: false, // false for descending
merged: function() {
var comments = this.get('comment') || [], // This gets wherever you've stored the comments array
messages = this.get('message') || [];// This gets wherever you've stored the messages array
var stream = Ember.A();
stream.pushObjects(comments.toArray());
stream.pushObjects(messages.toArray());
return Em.ArrayProxy.createWithMixins(Ember.SortableMixin, {
content: stream,
sortProperties: this.sortProperties,
sortAscending: this.sortAscending
});
}.property('messages.@each', 'comments.@each')
});
希望这也适合您。仅供引用,对于我的示例,我的 Controller 实际上是渲染的 Controller ,因此我没有在 route 为其设置模型。我的 Controller 上只有属性,比如说,注释和消息,它们不断更新为 RecordArray。
因此,对于您的示例,您可能需要观察 .property('model.messages.@each', 'model.comments.@each')
关于ember.js - 合并 route 的两个模型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699040/