Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Underscore Method 'find' on a Backbone Collection

I'm trying to use the Underscore method 'find' on a collection but it is not giving me the results I expected:

I have a base model with no defaults, and a default collection. The models in my collection have only two attributes: tranId(a guid as a string), and perform(a function to perform).

I'm trying to find the item in the collection that matches the tranId that I pass it...

    var tranId = "1a2b3c";

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

Found is always undefined, even though the debugger shows that my collection does, indeed have an item in it where tranId matches my variable. I am unable to set a breakpoint at the return statement to see what item.tranId equates to. I have also tried this...

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

But, same thing. 'found' is always undefined. What am I doing wrong here?

like image 403
Pop-A-Stash Avatar asked Jul 16 '12 14:07

Pop-A-Stash


2 Answers

Backbone collection implements many of the Underscore functions, so you could do this:

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

Also to debug if the values are not what you expect try:

var found = myCollection.find(function(item){
        console.log('Checking values', item, item.get('tranId'), tranId);   
        return Number(item.get('tranId')) === tranId;
});
like image 57
Daniel Aranda Avatar answered Oct 27 '22 01:10

Daniel Aranda


A more simple one:

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

See here for details.

If you must use Underscore method:

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

Because myCollection.models is an array, myCollection not.

I prefer the former one.

like image 21
Frank Fang Avatar answered Oct 26 '22 23:10

Frank Fang