【问题标题】:How to sort a collection in Backbone如何在 Backbone 中对集合进行排序
【发布时间】:2012-08-17 12:32:48
【问题描述】:

我想在将集合传递给模板之前对其进行排序。我在视图的渲染功能中使用

CollectionForTelplate : this.Collection

我的获取方式是

var self = this;
//fetch done here
if (Collection.length > 0) {
    _.each(Collection, function(Model) {
        JSON.stringify(Model);
    }, this);
};
self.Collection = Collection;
self.render;
  1. 还有其他方法可以将集合传递给模板吗?
  2. 如何根据模型的字符串字段对集合进行排序,比如 Model.name ?我尝试在集合中编写一个比较器并在视图中编写一个排序函数,但不幸的是;它对我不起作用

【问题讨论】:

  • 很抱歉,但是使用提供的代码 sn-ps,无法提供太多帮助。在您的代码中,您没有将任何集合数据传递给模板,没有提供您的渲染功能,您的比较器是什么样的,........请提供完整代码

标签: backbone.js


【解决方案1】:

实现您的Collectioncompatarator 函数,在docs 中定义为

如果你定义了一个比较器,它将用于维护集合 按顺序排列。

这样,您的收藏将在添加、删除等之后自动按排序顺序保存。您可以将其实现为sort

comparator: function(model1, model2) {
  if (model1 comes before model 2) {
    return -1;
  } else if (model1 is equal to model 2) {
    return 0;
  } else { // model1 comes after model 2
    return 1;
  }
}

sortBy

comparator: function(model) {
  // Return some numeral or string attribute and it will be ordered by it
  // == smaller numbers come first / strings are sorted into alphabet order
  return model.get('someAttribute');
}

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    有没有其他方法可以将集合传递给 模板?

    是的,收藏有一个toJSON() method,所以你可以简单地做类似的事情

    render: function() {
      this._template({list: this.toJSON()}); //assuming your template is already compiled
      return this;
    }
    

    你如何根据模型的字符串字段对集合进行排序,比如 型号名称 ?我尝试在集合中编写一个比较器并进行排序 功能视图,但不幸的是;它不适合我

    您可以简单地在集合上定义 comparator 函数,它应该保持自身排序,这是文档中给出的示例

    chapters.comparator = function(chapter) {
      return chapter.get("page");
    };
    

    【讨论】:

      猜你喜欢
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2019-04-24
      相关资源
      最近更新 更多