2013-11-21 144 views
4

我正在使用骨幹和木偶,骨幹收集比較器

我想對我的收集和渲染視圖進行排序。

但有些奇怪的事情發生。

'/ API/NOTE /的GetList',它返回(和它調用時收集通過視圖進行初始化)

[{"id":22,"name":"Test2","isPublic":1},{"id":11,"name":"Test1","isPublic":1},{"id":33,"name":"Test3","isPublic":1}] 

,這是我的收藏,

define [ 
    'models/Note' 
], 
(Note) -> 
    class NoteCollection extends Backbone.Collection 

     model : Note 
     url : '/api/note/getList' 

     comparator : (item) => 
      console.log item.get 'id' 
      return item.get 'id' 

和console.log print

22 
22 
11 

print'22'twice?也不排序。

我應該怎麼做排序集合?

[編輯]

這是我compisteView是初始化集合

define [  
    'hbs!./noteCollection_tpl' 
    './noteItemView' 
    'collections/NoteCollection' 
], 
(noteCollection_tpl, noteItemView, NoteCollection) -> 
    class NoteCollectionView extends Backbone.Marionette.CompositeView 
     template : noteCollection_tpl 
     itemView : noteItemView 
     itemViewContainer : '.noteListContainer' 
     className : 'noteWrap' 

     initialize : (options) -> 
      @collection = new NoteCollection() 

@collection =新NoteCollection()=>這個自動運行,我認爲獲取。

+0

如果您打印收集,訂單是什麼?比較函數用於對集合進行排序,因此查看它打印出的內容並不一定會給你訂單。 – elevine

+0

當集合被初始化時,url被調用。如何在URL加載後掛鉤事件? –

回答

10

的問題是,您使用的是綁定的功能比較:

comparator : (item) => 

和被混淆骨幹的「有多少爭論也比較採取」檢查。從fine manual

比較collection.comparator

[...]比較器可以被定義爲一個sortBy(通過一個函數,一個參數),作爲排序(傳遞需要兩個參數的比較功能),[...]

如果我們看看裏面sort,我們看到:

if (_.isString(this.comparator) || this.comparator.length === 1) { 
    this.models = this.sortBy(this.comparator, this); 
} else { 
    this.models.sort(_.bind(this.comparator, this)); 
} 

因此,如果comparator是一個函數,它接受一個參數(即, comparator.length === 1),則將使用sortBy,比較器將獲得一個參數;但是,如果comparator是不帶一個參數的函數,則使用標準sort,比較器將傳遞兩個參數。

如果你看你的comparator被調用,你會看到它得到兩個的論點。這怎麼會發生?如果comparator.length不是一個,就會發生這種情況。由於CoffeeScript實現=>的方式,您的comparator結尾爲0的length;例如:

class C 
    m1: (x) -> x 
    m2: (x) => x 

c = new C 
console.log(c.m1.length) 
console.log(c.m2.length) 

會給你在控制檯10

演示http://jsfiddle.net/ambiguous/GAAap/

如果你看的JavaScript這樣的:

class C 
    m: (x) => x 

你會看到,this function is used

__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; 

產生=>方法。注意那裏的return function() { ... }?這意味着每個=>方法將聲稱具有零的length。恭喜,我認爲您已經重新發現了CoffeeScript中的一個錯誤。

如果您使用您的comparator標準->方法:

comparator: (item) -> item.id 

那麼CoffeeScript中不會搞砸你的comparatorlength價值,你的排序將開始變得有意義。

演示http://jsfiddle.net/ambiguous/WXDcJ/


貌似epidemian已經報告了這個bug:

https://github.com/jashkenas/coffee-script/pull/2872


執行摘要:不要將=>用於骨幹收集比較器功能。