Giovanni Bitliner
Giovanni Bitliner

Reputation: 2072

Backbone collection, countBy errors

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'

Upvotes: 4

Views: 522

Answers (2)

mu is too short
mu is too short

Reputation: 434745

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.

Upvotes: 7

Koenyn
Koenyn

Reputation: 704

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

Upvotes: 0

Related Questions