11

我正在尝试在集合上使用下划线方法“查找”,但它没有给我预期的结果:

我有一个没有默认值的基本模型和一个默认集合。我收藏的模型只有两个属性:tranId(作为字符串的 guid)和 perform(要执行的函数)。

我正在尝试在集合中找到与我传递的 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;
    });

但是,同样的事情。'found' 总是未定义的。我在这里做错了什么?

4

3 回答 3

22

Backbone 集合实现了许多下划线功能,因此您可以这样做:

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;
});
于 2012-07-16T14:50:20.847 回答
11

一个更简单的:

var found = myCollection.findWhere({'tranId': tranId})

有关详细信息,请参见此处

如果必须使用下划线方法:

var found = _.find(myCollection.models, function(item){
    return item.get('tranId') === tranId;
});

因为 myCollection.models 是一个数组,所以 myCollection 不是。

我更喜欢前者。

于 2013-10-10T09:24:58.383 回答
6

在 Backbone(管理模型列表的对象)和 Underscore(对象列表)中,集合的含义并不完全相同。你应该传递给_.find的是myCollection.models

_.find(myCollection.models, function(model) {
    return model.get('tranId')===tranId;
});

正如@Daniel Aranda 解释的那样,Backbone 代理在集合上使用下划线方法,您可以将示例编写为

myCollection.find(function(model) {
    return model.get('tranId')===tranId;
});

最后,如果tranId是您的模型 ID,您可以将 id 设置为 idAttribute并通过使用简化整个事情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);

还有一个小提琴http://jsfiddle.net/rYPLU/

于 2012-07-16T15:06:31.750 回答