Backbone.js collection and sortedIndex always returning 0

自作多情 提交于 2019-12-12 03:05:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!