Reputation: 10044
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?
Upvotes: 0
Views: 197
Reputation: 434606
Backbone collections have some Underscore methods mixed in so you can use the Underscore methods directly on the collection instance:
console.log(comments.pluck('created'));
comments.each(function(com) { console.log(com) });
Demo: http://jsfiddle.net/ambiguous/3jRNX/
This one:
console.log(_.size(comments));
works fine for you because _.size
looks like this:
_.size = function(obj) {
return _.toArray(obj).length;
};
and _.toArray
calls the collection's toArray
:
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
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 _.size
has a different implementation so your _.size
call is likely to break during an upgrade.
Upvotes: 1
Reputation: 1128
You'll want to call pluck directly on the collection, as the Collection class supports it:
http://documentcloud.github.com/backbone/#Collection-pluck
So instead of:
_.pluck(comments, 'created')
You chould call:
comments.pluck('created');
Upvotes: 1