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: /
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/netroworx/KLYL9/
Share Improve this question asked Jul 1, 2013 at 9:29 Greg Pagendam-TurnerGreg Pagendam-Turner 2,5525 gold badges35 silver badges52 bronze badges2 Answers
Reset to default 10Change 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.
_.each
accepts an array as first argument, but you passed a Collection
.
Just use the Collection.each
method:
actionCollection.each(function(item){
//do stuff with item
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745655967a4638544.html
评论列表(0条)