我有一个很棒的函数,可以遍历集合中的模型以获取属性和值。如果找到该值,则返回true。
在看了很多文档之后,我仍然对如何正确地遍历集合以及如何搜索它感到有点困惑。由于underscorejs (在我的例子中是lodash)被挂接到backbone中,所以我使用.each遍历集合
我没有在if (model.get(attribute)===value)后面放一个else,因为它会在遍历整个集合之前返回false。回调函数听起来不必要的复杂--但也许我错了(我几个月前就开始使用JS了)
我将很高兴得到提示和/或更好的解决方案;-)并解释一下。提前谢谢。
我使用requirejs,这就是为什么我要通过_,Bacbkone...
以下是集合的外观:
function (_, Backbone, AppModels) {
var QueriesCollection = Backbone.Collection.extend({
model : AppModels.QueryModel,
search: function (attribute, value) {
var found = false;
this.each(function (model) {
if (model.get(attribute)===value) {
found = true;
}
});
return found;
}
});
return {
QueriesCollection: QueriesCollection
};
});发布于 2012-12-09 08:41:24
您还可以使用下划线some (也称为any),它与search函数几乎相同,只是它接受一个函数参数作为其谓词,而不是键/值:
如果列表中的任何值通过迭代器真值测试,则
返回true。如果找到真元素,则短路并停止遍历列表。
使用它的实现更直接一些:
search: function (attribute, value) {
return this.some(function(x) {
return x.get(attribute) === value;
});
}https://stackoverflow.com/questions/13783443
复制相似问题