javascript - Backbone each undefined - Stack Overflow

Why is the item variable undefined in this Backbone example?var Action = Backbone.Model.extend({defaul

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
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745655967a4638544.html

相关推荐

  • javascript - Backbone each undefined - Stack Overflow

    Why is the item variable undefined in this Backbone example?var Action = Backbone.Model.extend({defaul

    8小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信