Collections 使用下划线方法';查找';关于主干集合
我试图在集合上使用下划线方法“find”,但它没有给出我预期的结果: 我有一个没有默认值的基本模型和一个默认集合。我的集合中的模型只有两个属性:tranId(作为字符串的guid)和perform(要执行的函数) 我试图在集合中找到与我传递的tranId匹配的项Collections 使用下划线方法';查找';关于主干集合,collections,backbone.js,find,underscore.js,Collections,Backbone.js,Find,Underscore.js,我试图在集合上使用下划线方法“find”,但它没有给出我预期的结果: 我有一个没有默认值的基本模型和一个默认集合。我的集合中的模型只有两个属性:tranId(作为字符串的guid)和perform(要执行的函数) 我试图在集合中找到与我传递的tranId匹配的项 var tranId = "1a2b3c"; var found = _.find(myCollection, function(item){ return item.tranId === tranId
var tranId = "1a2b3c";
var found = _.find(myCollection, function(item){
return item.tranId === tranId;
});
Found始终是未定义的,即使调试器显示我的集合中确实有一个tranId与我的变量匹配的项。我无法在return语句处设置断点,以查看item.tranId等同于什么。我也试过这个
var found = _.find(myCollection, function(item){
return item.get('tranId') === tranId;
});
但是,同样的事情。”“已找到”始终是未定义的。我做错了什么?主干收集实现,因此您可以执行以下操作:
var found = myCollection.find(function(item){
return Number(item.get('tranId')) === tranId;
});
如果值不是您期望的值,也要进行调试,请尝试:
var found = myCollection.find(function(item){
console.log('Checking values', item, item.get('tranId'), tranId);
return Number(item.get('tranId')) === tranId;
});
集合在主干(管理模型列表的对象)和下划线(对象列表)中的含义并不完全相同。您应该传递给
\uu.find
的是myCollection.models
_.find(myCollection.models, function(model) {
return model.get('tranId')===tranId;
});
正如@Daniel Aranda所解释的,主干代理和您可以将您的示例编写为
myCollection.find(function(model) {
return model.get('tranId')===tranId;
});
最后,如果tranId
是您的模型ID,您可以使用get
var M=Backbone.Model.extend({
idAttribute: "tranId"
});
var C=Backbone.Collection.extend({
model:M
});
var myCollection=new C([
{tranId:'not this one'} ,
{tranId:'another'} ,
{tranId:'1a2b3c'}
]);
myCollection.get(tranId);
还有一把小提琴一把更简单的小提琴:
var found = myCollection.findWhere({'tranId': tranId})
有关详细信息,请参阅
如果必须使用下划线方法:
var found = _.find(myCollection.models, function(item){
return item.get('tranId') === tranId;
});
因为myCollection.models是一个数组,所以myCollection不是
我更喜欢前者。谢谢,这很有效。为什么下划线方法的工作方式不同?还应该注意,tranId是一个字符串,而不是一个数字。因此,不需要类型转换。@JoelCDoyle如果要直接使用下划线方法,最好使用myCollection.models,因为它是模型的原始数组——类型转换是为了防止严格的数据类型比较出现问题:非常好。我喜欢单线解决方案!非常有用,谢谢!作为旁注,请记住主干模型的默认
idAttribute
是id
字段,以获取更多信息