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?
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;
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With