简体   繁体   English

BackboneJS:对链接项的集合进行排序

[英]BackboneJS: Sorting collection of linked items

I have some trouble figuring out how to sort a BackboneJS collection containing linked items. 我在弄清楚如何对包含链接项的BackboneJS集合进行排序时遇到了一些麻烦。 Is it at all possible to do efficiently? 根本有可能做到高效吗? (I am thinking of making one returning the count of previous elements, but that is really inefficient) (我正在考虑让一个返回先前元素的计数,但这确实效率不高)

What should the comparator be? 比较器应该是什么? - and is a double linked list required? -是否需要双链表?

My items look like 我的物品看起来像

[ { id: 1, name: 'name', previousItem: 2 }, { id: 2, name: 'othername', previousItem: null } ] [{id:1,名称:“名称”,previousItem:2},{id:2,名称:“ othername”,previousItem:null}]

Here is the basic code to build the collection. 这是构建集合的基本代码。 I'm assuming you are using a Backbone Model here. 我假设您在这里使用骨干模型。 In the loop, you need to add your models to the front of the collection (unshift) since you only know the previous item. 在循环中,由于您只知道上一个项目,因此需要将模型添加到集合的最前面(不更改)。

The key here is knowing what the last item is though. 这里的关键是知道最后一个项目是什么。 If you don't know it, then this will not work. 如果您不知道,那就行不通了。

model = frontItem;
while (model != null) {
   collection.unshift(model);
   model = model.attr('previousItem')    
}

there is a discussion about this on github , you can also use comparator , if you want to use comparator you need underscore github上有关于此的讨论,您也可以使用比较器 ,如果要使用比较 ,则需要下划线

var PhotoCollection = Backbone.Collection.extend({
    model: Photo,
    comparator: function(item) {
        return item.get('pid');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM