0

我正在使用几个主干集合,有时我需要根据某些标准访问其中的一部分。

方法一

正如这个问题中已经说明的那样,在集合本身上使用filter()会返回一个模型数组,而不是另一个集合。这可以在简单的情况下工作,但它具有丢失集合的方法连接的效果,因为模型的普通数组不会在集合中定义所有方法。

方法二

该问题的答案建议创建一个新集合,将模型数组传递给构造函数。这可行,但有每次调用集合的构造函数的副作用,因此每次过滤集合时可能在此处定义的任何事件绑定都会堆叠。

那么根据某些过滤条件创建子集合的正确方法是什么?

我应该使用方法 1 并创建更多过滤方法而不是依赖方法链接吗?

我应该使用方法 2 并避免在集合的构造函数中绑定事件吗?

4

2 回答 2

1

Personally I would create more filtering methods on the collection, because it has the additional benefit of encapsulating logic inside the collection.

You could also try to reuse the existing collection. I was toying around with the idea, and arrived at something like this:

var Collection = Backbone.Collection.extend({
  //Takes in n arrays. The first item of each array is the method you want
  //to call and the rest are the arguments to that method. 
  //Sets the collection.models property to the value of each successive filter
  //and returns the result of the last. Revers the collection.models to its original value.
  chainFilters: function(/*args..*/) {
    var models = this.models;
    try {
      filters = _.toArray(arguments);
      _.each(filters, function(filter) {
         this.models = filter[0].apply(this, _.rest(filter));
      }, this);
    } catch(err) {
      this.models = models;
      throw err;
    }

    var filtered = this.models;
    this.models = models;
    return filtered;   
  }
});

Usage:

var results = collection.chainFilters(
  [ collection.filter, function(model) { return model.get('name') === 'foo'; } ],
  [ collection.someMethod, 'someargument' ],
  [ collection.someOtherMethod ]
);

Here's a working sample. It's a bit peculiar, I know.

于 2013-01-07T17:51:14.363 回答
0

这取决于用例。如果您希望这些模型更新视图,那么您可能需要一个新集合,否则您将无法获得好的响应式模板更新。如果您只是想让模型遍历或操作数据而不用担心数据更新,那么请使用数组 + underscore.js。

尝试使用数组,如果您发现自己编写了很多样板代码,这些代码已经在集合中但不在 underscore.js 中,那么就开始使用集合。

于 2013-01-07T15:37:56.710 回答