2011-09-26 74 views
0

我无法获得sortedIndex下划线方法返回有用的值。我有一个比较器的集合,并按顺序正确添加模型。我只想知道新模型的潜在索引,并且sortedIndex方法返回0我尝试的事情。Backbone.js收集和sortedIndex始终返回0

var Chapter = Backbone.Model; 
var chapters = new Backbone.Collection; 

chapters.comparator = function(chapter) { 
    return chapter.get("page"); 
}; 

chapters.add(new Chapter({page: 9, title: "The End"})); 
chapters.add(new Chapter({page: 5, title: "The Middle"})); 
chapters.add(new Chapter({page: 1, title: "The Beginning"})); 

var foo = new Chapter({ page: 3, title: 'Bar' }); 

// Will always return 0 no matter the value of page in foo. 
console.log(chapters.sortedIndex(foo)); 

我知道有一些错误在那里,或许这就是sortedIndex没有打算,但我不能确定任何一种方式。

回答

3

问题是Underscore.js对集合的comparator函数一无所知,并期望比较器作为sortedIndex函数的参数。这将按预期工作:

console.log(chapters.sortedIndex(foo, chapters.comparator));