Backbone.js 集合和排序索引始终返回 0

发布于 2024-12-06 15:47:13 字数 676 浏览 0 评论 0原文

我无法让 sortedIndex 下划线方法返回有用的值。我有一个带有比较器的集合,它按顺序正确添加模型。我只想知道新模型的潜在索引,而无论我尝试什么,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));

我知道那里有问题,或者也许这不是排序索引的意图,但我不确定哪种方式。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒解孤独 2024-12-13 15:47:13

问题是 Underscore.js 对集合的 comparator 函数一无所知,并期望 comparator 作为 sortedIndex 函数的参数。这将按预期工作:

console.log(chapters.sortedIndex(foo, chapters.comparator));

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文