2014-09-04 56 views
1

我有一個Backbone.js應用程序與木偶插件。這裏面有一個CompositeView中(和ItemViews)呈現的集合,我需要把它按以下方式進行排序:Backbone.js自定義收集排序

  1. 用戶可以重新呈現ItemViews(使用jQuery排序插件),而該用戶偏好被保存在一個cookie模型ID數組的形式
  2. 在每次重新載入時,我想對獲取的集合進行排序,使其與前述的用戶首選項順序相同。

我試圖在onRender鉤子中手動排序collection.models數組,然後重新渲染它,但這種集合操作只是「感覺不對」(並導致無盡的渲染循環)。

是否有某種更優雅的解決方案來對集合進行排序,使模型與其他數組中定義的模型ID具有相同的順序?

+0

看看http://backbonejs.org/#Collection-comparator – Palpatim 2014-09-04 19:42:31

回答

3

嘗試使用集合上的Backbone.Collection#comparator方法,該方法將使用ID數組訪問cookie並使用它返回1或-1。

比較功能採取兩種模式,並返回-1,如果他們是同一職級和1,如果第一個模型應該來後的第一款車型要來的前一秒,0。

var MyCollection = Backbone.Collection.extend({ 

    comparator: function(model_a, model_b) { 
     // In real app array comes from cookie 
     var order = [5, 2, 1, 4, 3], 
      a_index = order.indexOf(model_a.id), 
      b_index = order.indexOf(model_b.id); 

     if (a_index > b_index) { 
      return 1; 
     } else if (a_index < b_index) { 
      return -1; 
     } else { 
      return 0; 
     } 
    } 

}); 

var my_collection = new MyCollection([ 
    { id: 1 }, 
    { id: 2 }, 
    { id: 3 }, 
    { id: 4 }, 
    { id: 5 } 
]); 

alert(my_collection.pluck('id')); 

這裏是jsfiddle這個例子

0

一種方法是將映對IDS的你的「自定義」列表和集合中與ID返回型號:

var items = [ 
    {id: 0, name: '1st', age: 40}, 
    {id: 1, name: '2nd', age: 50}, 
    {id: 2, name: '3rd', age: 60} 
]; 

// order stored in cookie or localstorage ^^ 
var sorted = [2, 1, 0]; 

// our source collection 
var collection = new Backbone.Collection(items); 

// this could be implemented as a collection method if necessary 
var sortedCollection = _.map(sorted, function (id) { 
    return collection.get(id); 
}); 


var sortedIds = sortedCollection.map(function (item) { return item.id }) 
console.log(sortedIds); 
// [2, 1, 0] 

jsbin with an example view