在Backbone.js的相反顺序排序字符串 [英] Sorting strings in reverse order with backbone.js
问题描述
我想以按相反的顺序Backbone.js的集合。有关于如何使用整数做previous答复,但没有用绳子。
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'));
以上code排序章节中的从A - >以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 版本 - 这是在示例中所示,这有一个参数,或排序 - 你可以返回更多的标准排序功能,其中文档说:
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,如果,如果他们是同一职级和1,如果第一个模型应该后的第一款车型应该的前一秒,0。
"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'));
所以,你应该得到作为一个响应:
So you should get as a response:
"The Middle", "The End", "The Beginning"
这篇关于在Backbone.js的相反顺序排序字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!