最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Backbone each undefined - Stack Overflow

matteradmin3PV0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 10

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.

_.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
});
Post a comment

comment list (0)

  1. No comments so far