Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone each undefined

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/

like image 243
Greg Pagendam-Turner Avatar asked Apr 15 '26 09:04

Greg Pagendam-Turner


1 Answers

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.

like image 90
Bas Slagter Avatar answered Apr 17 '26 21:04

Bas Slagter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!