使用backbone.js以相反的顺序对字符串进行排序 [英] Sorting strings in reverse order with backbone.js

查看:10
本文介绍了使用backbone.js以相反的顺序对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以相反的顺序对 Backbone.js 集合进行排序.之前有关于如何使用整数执行此操作的回复,但没有关于字符串的回复.

I'm trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("title");
};

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

alert(chapters.pluck('title'));

上面的代码将章节从 A -> Z 排序,但是我如何编写一个比较器将它从 Z -> A 排序?

The above code sorts the chapters from A -> Z, but how do I write a comparator that sorts it from Z -> A?

推荐答案

您可以使用两个版本的比较器函数,一个是 sortBy 版本 - 如示例中所示,采用一个参数,或 sort - 您可以返回一个更标准的排序函数,文档 说:

There are two versions of the comparator function that you can use, either the sortBy version - which was shown in the example, which takes one parameter, or sort - which you can return a more standard sort function, which the documentation says:

"sortBy" 比较器函数接受一个模型并返回一个数字或字符串值,该模型应该相对于其他模型进行排序.排序"比较器函数采用两个模型,如果第一个模型应该在第二个模型之前,则返回 -1,如果它们的等级相同,则返回 0,如果第一个模型应该在之后,则返回 1.

"sortBy" comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others. "sort" comparator functions take two models, and return -1 if the first model should come before the second, 0 if they are of the same rank and 1 if the first model should come after.

所以在这种情况下,我们可以编写一个不同的比较器函数:

So in this case, we can write a different comparator function:

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapterA, chapterB) {
  if (chapterA.get('title') > chapterB.get('title')) return -1; // before
  if (chapterB.get('title') > chapterA.get('title')) return 1; // after
  return 0; // equal
};

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

alert(chapters.pluck('title'));

所以你应该得到回应:

"The Middle", "The End", "The Beginning"

这篇关于使用backbone.js以相反的顺序对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆