Backbone.js的收集和sortedIndex总是返回0 [英] Backbone.js collection and sortedIndex always returning 0
问题描述
我遇到麻烦 sortedIndex
强调方法返回一个有用的值。我有一个比较的集合,而这为了正确添加模型。我只是想知道新模式的潜力指数,而 sortedIndex
方法返回0,不管我试试。
I'm having trouble getting the sortedIndex
underscore method to return a useful value. I have a collection with a comparator, and that's adding models correctly in order. I would just like to know the potential index of a new model, and the sortedIndex
method is return 0 matter what I try.
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没有打算,但我不能确定两种方式。
I know there's something wrong in there, or perhaps that's no the intention of sortedIndex but I'm unsure either way.
推荐答案
问题是Underscore.js一无所知比较集合
函数,并预计比较作为 sortedIndex
函数的参数。这将如预期:
The problem is Underscore.js knows nothing about the comparator
function of the collection and expects comparator as an argument of sortedIndex
function. This will work as expected:
console.log(chapters.sortedIndex(foo, chapters.comparator));
这篇关于Backbone.js的收集和sortedIndex总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!