初始化后对 Backbone 集合进行排序 [英] Sorting a Backbone Collection After initialization
问题描述
我正在使用 Backbone.js 来呈现项目列表,例如书籍.列表呈现后,用户可以选择对其进行排序.因此,如果用户单击按标题排序"或按作者姓名排序",列表将在客户端自行排序.
I am using Backbone.js to render a list of items e.g Books. After the list is rendered, there are options for user to sort them. So if user clicks on Sort By Title, or Sort By Author Name the list will sort itself on the client side.
window.Book = Backbone.Model.extend({
defaults: {
title: "This is the title",
author: "Name here"
},
在 Backbone 应用程序的上下文中完成这种排序的最佳方法是什么.我是否在 AppView 中使用了 jQuery dom 排序器?
What is the best way to accomplish this sort using in the context of a Backbone application. Do I use a jQuery dom sorter in the AppView?
推荐答案
有一个关于这个主题的讨论,你可能想看看:https://github.com/documentcloud/backbone/issues/41.
There's a discussion on this very topic that you might want to look at: https://github.com/documentcloud/backbone/issues/41.
简而言之,当用户选择按 X 排序"时,您可以:
The short of it is that when a user selects 'sort by X', you can:
- 在集合上设置
comparator
函数 - 调用集合的
sort
函数(这将触发一个sort
事件) - 在您的视图中监听
sort
事件,并(清除和)重绘项目
- Set the
comparator
function on the Collection - Call the Collection's
sort
function (which will trigger asort
event) - Listen for the
sort
event in your View, and (clear and) redraw the items
处理步骤 1 & 的另一种方法2 是拥有自己的方法,该方法调用集合的 sortBy
方法,然后触发您的 View 可以侦听的自定义事件.
Another way to handle steps 1 & 2 is to have your own method that calls the Collection's sortBy
method and then triggers a custom event that your View can listen to.
但似乎清除和重绘是对视图进行排序并使它们与集合的排序顺序保持同步的最简单(甚至可能是最快)的方法.
But it seems to be the case that clearing and redrawing is the easiest (and maybe even the fastest) way to sort your View's and keep them in sync with your Collection's sort order.
这篇关于初始化后对 Backbone 集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!