[英]Backbone.js filter collection returns an object, not a collection
I'm trying to filter a collection of models, but filter only seems to be returning an object and not a collection. 我正在尝试过滤模型的集合,但是过滤器似乎只返回一个对象而不是一个集合。 From what I've read, wrapping the filter function in _() will force it to use underscore.js built in filter, and return the same type. 根据我的阅读,将filter函数包装在_()中将迫使它使用内置在filter中的underscore.js,并返回相同的类型。 But this doesn't seem to be working. 但这似乎不起作用。 Code is below, any thoughts? 代码在下面,有什么想法吗?
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');
}
This is my output: 这是我的输出:
clients is a collection
clients is an object
Assuming you instantiated your clients
collection like this: 假设您以如下方式实例化了clients
集合:
var Client = Backbone.Model.extend({});
var Clients = Backbone.Collection.extend({
model: Client
});
var clients = new Clients();
Then all you'd need to do is: 然后,您需要做的就是:
clients = new Clients(clients.filter(function (client) {
return client.get('case_studies').length
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.