Backbone.js collection and sortedIndex always retu

2019-09-16 16:18发布

问题:

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));