4

I have a collection that i want to group by counting the same values in its attribute. So i execute this:

_.countBy(T.collection,function(model){
    return model.get('text')
})

where attribute is a string. This string is able to have letters (A-z), ':' and '_' (underscore). It hasn't whitespace.

But the code throws

Cannot call method 'get' of undefined.

I have also tried with

T.collection.countBy(function(model){
    return model.get('text')
})

but it throws

Object [object Object] has no method 'countBy'

user3335966
  • 2,673
  • 4
  • 30
  • 33
Giovanni Bitliner
  • 2,032
  • 5
  • 31
  • 50

2 Answers2

7

countBy isn't one of the Underscore methods that are mixed into collections so, as you've seen, this won't work:

T.collection.countBy(function(model){ return model.get('text') });

And a collection isn't an array so this won't work either:

_.countBy(T.collection,function(model){ return model.get('text') });

When you do that, model won't be a model in the collection, it will be one of the values for T.collection's object properties; for example, this:

_({where: 'is', pancakes: 'house?'}).countBy(function(x) { console.log(x); return 0 });​​​

will give you is and house? in the console.

However, T.collection.models is an array, an array of models at that. That means that this should work:

_.countBy(T.collection.models, function(model) { return model.get('text') });

I'd recommend adding that as a method on your collection so that outsiders don't have to mess around with the collection's models property.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

I can make 2 suggestions:

1: somewhere in the collection "model" is undefined. So when you do model.get('text') it's throwing an error because you can't fire a method on an undefined variable. Perhaps your function should be:

_.countBy(T.collection,function(model){
    return model ? model.get('text') : ''; // or maybe a null, depending on what you want
});

2: to debug use firebug's console to check what the values of model are i.e.

_.countBy(T.collection,function(model){
    console.log('model', model);
    return model ? model.get('text') : '';
});

Hope this helps

Koenyn
  • 694
  • 4
  • 16
  • I've never worked with underscore.js, but it's more than likely that your collection has got some prototype items in it. you might want to look at this post about javascript's hasOwnProperty() http://stackoverflow.com/questions/2600085/hasownproperty-in-javascript – Koenyn Oct 25 '12 at 12:13
  • I have already tried in this way, checking if there was some bad result of `model.get('text')` , but nothing is irregular. I have also tried to subsistute the characters ':' and '_' with '', but nothing has changed. – Giovanni Bitliner Oct 25 '12 at 13:09