2012-07-25 44 views
13

我正在嘗試對Marionette.CompositeView中的集合進行排序。
我有一個集合,看起來像這樣:在CompositeView中對集合進行排序的最佳方法

[ 
    {id: 1, name: 'bar'}, 
    {id: 2, name: 'boo' }, 
    {id: 3, name: 'foo' } 
] 

我需要通過ID集合以相反的順序進行排序。
其實它只有當我重新加載頁面時才起作用。
當我添加一個新模型時,新項目顯然是隨機添加到列表中。
如果我刷新頁面,它們將很好地排序。

我的問題是:
1)如何解決問題,當我添加一個新的模型?
2)有可能改進代碼?


這裏是我的代碼:

return Marionette.CompositeView.extend({ 

    initialize: function() { 
     this.collection.fetch(); 
    }, 

    onRender: function() { 
     var collection = this.collection; 

     collection.comparator = function (collection) { 
      return - collection.get('id'); 
     } 
    }, 

    onSuccess: function() { 
     this.collection.add(this.messageModel); 
     this.collection.sort(); // the messageModel seems to be added 
           // apparently randomly to the list. 
           // only if I refresh the page it will be ok 
    } 
}) 

回答

1

可以在創建集合聲明的.comparator?從您的代碼中,.comparator僅存在於onRender函數內的局部變量var collection中。如果正確定義的收集必須自動排序,你不需要增加新的模型

var Chapters = new Backbone.Collection({ 
    comparator = function(chapter) { 
     return chapter.get("id"); 
    }; 
}); 
14

對於木偶> = 2.0CollectionViewCompositeViewmaintain sorting by default之後調用的.sort。

對於牽線木偶< 2.0和> = 1.3.0

var MySortedView = Backbone.Marionette.CollectionView.extend({ 

    // ... 

    appendHtml: function(collectionView, itemView, index) { 
    // Already sorted when buffering. 
    if (collectionView.isBuffering) { 
     Backbone.Marionette.CollectionView.prototype.appendHtml.apply(this, arguments); 
    } 
    else { 
     var childrenContainer = $(collectionView.childrenContainer || collectionView.el); 
     var children = childrenContainer.children(); 
     if (children.size() === index) { 
     childrenContainer.append(itemView.el); 
     } else { 
     childrenContainer.children().eq(index).before(itemView.el); 
     } 
    } 
    } 

}); 

對於牽線木偶< 2.0或< 1.3.0(以前一樣沒有緩衝):

var MySortedView = Backbone.Marionette.CollectionView.extend({ 

    // ... 

    appendHtml: function(collectionView, itemView, index) { 
    var childrenContainer = $(collectionView.childrenContainer || collectionView.el); 
    var children = childrenContainer.children(); 
    if (children.size() === index) { 
     childrenContainer.append(itemView.el); 
    } else { 
     childrenContainer.children().eq(index).before(itemView.el); 
    } 
    } 

}); 

CollectionView和CompositeView是一樣的。

+0

GitHub的鏈接是死了:-( – ErichBSchulz 2013-04-25 10:31:14

+0

GitHub的鏈接是不是死了:-) – Ziggy 2014-01-28 16:48:44

+1

Github的鏈接又是死。 – abhaga 2014-09-02 12:38:21

3

我相信木偶傢伙正在考慮把它建成木偶,但是直到那個時候,我已經建立了一個叫做Sorted的小混蛋,你可以將它們混合到你的CollectionViewCompositeView課程中。它在生產環境中被大量用於Gitter很長一段時間,我們發現它工作得很好..

相關問題