问题
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));
I know there's something wrong in there, or perhaps that's no the intention of sortedIndex but I'm unsure either way.
回答1:
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));
来源:https://stackoverflow.com/questions/7553895/backbone-js-collection-and-sortedindex-always-returning-0