2013-11-21 145 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


执行摘要:不要将=>用于骨干收集比较器功能。