初始化后对 Backbone 集合进行排序 [英] Sorting a Backbone Collection After initialization

查看:18
本文介绍了初始化后对 Backbone 集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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:

  1. 在集合上设置comparator函数
  2. 调用集合的sort函数(这将触发一个sort事件)
  3. 在您的视图中监听 sort 事件,并(清除和)重绘项目
  1. Set the comparator function on the Collection
  2. Call the Collection's sort function (which will trigger a sort event)
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆