2013-04-22 52 views
2

说我有这样一个模型:ember.js - 计算性能结合2的hasMany

App.Document = DS.Model.extend 
    users: DS.hasMany('App.User') 
    contacts: DS.hasMany('App.Contact') 

什么是创建一个计算的属性,将结合两个的hasMany关系,这样的最佳方式:

people: (-> 
    users.toArray().concat(contacts.toArray()).sort (a, b) -> 
    Em.Compare(a.get('name'), b.get('name')) 
).property('users.[]', 'contacts.[]') 

难道还有比我粗略估计上面,将应用排序,并考虑到如果记录数组是空的更好的办法?

回答

0

不知道这是否就是你要找的东西,但我认为你必须使用property('[email protected]')代替property('users.[]'),改变Em.Compare...Em.compare...(小写)

我做了一个sample来说明其User,ContactDocument

其中一个文件没有与其关联的联系人,且一个没有联系人或/或用户。 people计算属性如下所示:

people: (-> 
    @get('users').toArray().concat(@get('contacts').toArray()).sort (a, b) -> 
    Ember.compare(a.get('fullName'), b.get('fullName')) 
).property('[email protected]', '[email protected]') 

排序对组合数组工作正常。

注:我不说咖啡很好;对不起,如果语法是不是100%正确

0

这是一个相关的解决方案:https://stackoverflow.com/a/15869936/844923

JSBin example

你可以做的正是你想到了什么,只是通过使用特殊的@each key

例链接示例:

stream: function() { 
    var post = this.get('post'), 
     bookmark = this.get('bookmark'), 
     photo = this.get('photo'); 

    var stream = []; 

    stream.pushObjects(post); 
    stream.pushObjects(bookmark); 
    stream.pushObjects(photo); 
    return stream; 
}.property('[email protected]', '[email protected]', '[email protected]'), 

然后对它们进行排序:

streamSorted: function() { 
    var streamCopy = this.get('stream').slice(); // copy so the original doesn't change when sorting 
    return streamCopy.sort(function(a,b){ 
     return a.get('publishtime') - b.get('publishtime'); 
    }); 
    }.property('[email protected]') 
+0

我一直提防@each的性能的原因。 – dagda1 2013-04-22 20:50:37

+0

您是否注意到使用它时的性能问题? – CraigTeegarden 2013-04-22 21:02:10

+0

是的,对数组的更改会导致整个事件重新计算 – dagda1 2013-04-23 04:26:05