2011-09-26 123 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));