初始化时对 Backbone 集合重新排序

发布于 2025-01-07 15:05:22 字数 367 浏览 5 评论 0原文

我正在尝试找到一种在视图的 initialize 函数中重新组织 Backbone 集合的方法。在我的集合中,我的模型具有以下属性:

id: ...,
name: ...,
sort: 2,
parent: 45

parent 属性是我感兴趣的。我想将 parent id 为 45 的所有模型移动到一个集合的开始。可能有 200 个模型,也许 30 个模型的父模型为 45,15 个模型的父模型为 50,等等...我想保持我移动的块的顺序与之前的顺序相同(按 < 排序) code>sort 属性首先,我想保持它的原始顺序)。

有什么想法吗?

I'm trying to find a way to reorganize a Backbone collection in the initialize function of a view. In my collection I have models that have attributes like:

id: ...,
name: ...,
sort: 2,
parent: 45

The parent property is what I am interested in. I would like to move all models that have a parent id of 45 to the beginning of a collection. There may be 200 models and maybe 30 have a parent of 45, 15 have a parent of 50, etc... I would like to the keep the chunk that I move in the same order it was in before (it's ordered by the sort property to begin with, I would like to keep it in that original order).

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

所有深爱都是秘密 2025-01-14 15:05:22

使用下划线的 groupBy

var mySorted = _.groupBy(collection.models, function (model) {
  return model.get('parent') === 45 ? 'top' : 'rest' ;
});

然后 mysorted.top 包含所有具有父级的45. mySorted.rest 显然包含其余部分;)

Use underscore's groupBy

var mySorted = _.groupBy(collection.models, function (model) {
  return model.get('parent') === 45 ? 'top' : 'rest' ;
});

Then mysorted.top contains all the ones with parent 45. mySorted.rest obviously contains the rest ;)

南街九尾狐 2025-01-14 15:05:22

在您的类上定义一个新的 比较器。这将使您的收藏按照您希望的任何顺序排列。

Define a new comparator on your class. This will keep your collection in any order you wish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文