我使用骨干的集合模型在骨干视图上显示字符串的排序列表。 这是模型和比较器:
var MenuItems = Backbone.Collection.extend({ comparator: function (a, b) { if (a.get('name') < b.get('name')) { return 1; } else if (b.get('name') > a.get('name')) { return -1; } }, model: MenuItem, url: '/items' });运行代码时,只对列表中十二个项目中的前六个进行排序,其余项目仍未排序。 当comparator: 'name'使用时,列表是完全排序的,但是当使用函数时,会出现此问题。
任何人都知道为什么会发生这种情况? 这可能是一个Backbone bug吗? 我使用的是Backbone 1.1.0
I am using backbone's collection model to display a sorted list of strings on a backbone view. Here is the model and the comparator:
var MenuItems = Backbone.Collection.extend({ comparator: function (a, b) { if (a.get('name') < b.get('name')) { return 1; } else if (b.get('name') > a.get('name')) { return -1; } }, model: MenuItem, url: '/items' });When the code is run, only the first six of the twelve items in the list are sorted, the rest remains unsorted. When comparator: 'name' is used the list is fully sorted, but when a function is used, this problem occurs.
Anyone know why this might be happening? Could this be a Backbone bug? I am using Backbone 1.1.0
最满意答案
这是一个有效的代码。
var MenuItems = Backbone.Collection.extend({ comparator: function (a, b) { if (a.get('name') < b.get('name')) { return -1; } else if (a.get('name') > b.get('name')) { return 1; } } });这是jsfiddle与输出,所以你可以比较http://jsfiddle.net/ek44Z/2/
主要问题是功能内容。 你需要在if语句中返回-1 ,并在else if比较a和b else if并返回1 。 基本上你的else if从未被调用过。
有一个很好的编码。
Here is a working code.
var MenuItems = Backbone.Collection.extend({ comparator: function (a, b) { if (a.get('name') < b.get('name')) { return -1; } else if (a.get('name') > b.get('name')) { return 1; } } });Here is jsfiddle with output so you can compare http://jsfiddle.net/ek44Z/2/
The main problem was with function content. You need return -1 in if statement and compare a and b in else if and return 1. Basically your else if have never been called.
Have a good coding.
更多推荐
发布评论