I send a model to a template. The model has a collection. In the template I echo some variables and functions:
console.log(comments);
console.log(_.size(comments));
console.log(comments instanceof App.Collections.Comments);
console.log(_.pluck(comments, 'created'));
_.each(comments, function(com) {
console.log(com);
});
The first three work, but the last two underscore functions don’t. Pluck gives 3x undefined and each doesn’t iterate.
Object { length=3, models=[3], _byId={...}, more...}
3
true
[undefined, undefined, undefined]
How do I get the underscore functions to work?
Backbone collections have some Underscore methods mixed in so you can use the Underscore methods directly on the collection instance:
Demo: http://jsfiddle.net/ambiguous/3jRNX/
This one:
works fine for you because
_.sizelooks like this:and
_.toArraycalls the collection’stoArray:which unwraps the collection’s data to give you the correct length. The above is taken from the 1.3.1 source, the current Github master version‘s
_.sizehas a different implementation so your_.sizecall is likely to break during an upgrade.