Backbone.js过滤器集合返回一个对象,而不是一个集合

时间:2013-05-31 18:30:13

标签: javascript backbone.js filter underscore.js

我正在尝试过滤一组模型,但过滤器似乎只返回一个对象而不是一个集合。根据我的阅读,在_()中包装过滤器函数将强制它使用过滤器中内置的underscore.js,并返回相同的类型。但这似乎并没有起作用。代码在下面,有什么想法吗?

    var clients = this.get('clients')

    if (clients instanceof Backbone.Collection) {
      console.log('clients is a collection');
    } else if (_.isObject(clients)) {
      console.log('clients is an object');
    } else if (_.isArray(clients)) {
      console.log('clients is an array');
    } else {
      console.log('clients is not known');
    }

    clients = _(clients.filter(function (client) {
      return client.get('case_studies').length;
    }));

    if (clients instanceof Backbone.Collection) {
      console.log('clients is a collection');
    } else if (_.isObject(clients)) {
      console.log('clients is an object');
    } else if (_.isArray(clients)) {
      console.log('clients is an array');
    } else {
      console.log('clients is not known');
    }

这是我的输出:

    clients is a collection
    clients is an object 

1 个答案:

答案 0 :(得分:1)

假设您实例化了clients这样的集合:

var Client = Backbone.Model.extend({});
var Clients = Backbone.Collection.extend({
  model: Client
});
var clients = new Clients();

然后您需要做的就是:

clients = new Clients(clients.filter(function (client) {
  return client.get('case_studies').length
}));