Why is the item variable undefined in this Backbone example?
var Action = Backbone.Model.extend({
defaults: {
"selected": false,
"name": "First Action",
"targetDate": "10-04-2014"
}
});
var Actions = Backbone.Collection.extend({
model: Action
});
var actionCollection = new Actions( [new Action(), new Action(), new Action(), new Action()]);
_.each(actionCollection, function(item) {
alert(item);
});
jsFiddle here: http://jsfiddle.net/netroworx/KLYL9/
Change it to:
actionCollection.each(function(item) {
alert(item);
});
And it works fine.
This because actionCollection is not an array, so _.each(collection) does not work but collection.each does because that function is build into Backbone collection.
That being said, this also works:
_.each(actionCollection.toJSON(), function(item) {
alert(item);
});
Because now the collection is an actual array.
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