gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:12:31 25 4
gpt4 key购买 nike

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

最佳答案

假设您像这样实例化了 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
}));

关于javascript - Backbone.js 过滤器集合返回一个对象,而不是集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16863614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com