1

我正在尝试过滤模型集合,但过滤器似乎只返回一个对象而不是一个集合。根据我的阅读,将过滤器函数包装在 _() 中将强制它使用 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 
4

1 回答 1

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
}));
于 2013-05-31T19:29:58.947 回答