使用比较器时,Backbone Collection是半排序的(Backbone Collection is Half

编程入门 行业动态 更新时间:2024-10-26 17:31:36
使用比较器时,Backbone Collection是半排序的(Backbone Collection is Half-Sorted When Comparator is Used)

我使用骨干的集合模型在骨干视图上显示字符串的排序列表。 这是模型和比较器:

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.

更多推荐

本文发布于:2023-07-31 10:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341914.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Backbone   Collection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!