"this.collection.each不是函数".不应该简单地说"每个"吗?

use*_*279 2 javascript jquery backbone.js underscore.js

我真的有两个问题.

控制台告诉我:"TypeError:this.collection.each不是函数"

在短期内,我很想知道为什么我的代码不起作用.

从长远来看,我更有兴趣知道它为什么不告诉我"每个"不是一个函数,因为这是我试图调用的方法.

PS我已经确认JQuery正确加载,并且在此代码加载之前,这不是问题.

相关的JavaScript是:

$(function(){

var items = [
        { name: 'Abe Lincoln', details: 'Is he that guy from that new reality show?'},
        { name: 'Captain Planet', details: 'He is our hero'},
        { name: 'Karthus', details: 'Press R'},
        { name: 'Your Mom', details: 'She misses me'},
        { name: 'Teddy Roosevelt', details: 'Makes the most interesting man in the world look boring'}
    ];

    var itemsCollectionView = new ListView({collection: items});
    Backbone.history.start();
});

var ListView = Backbone.View.extend({

    el: '#the-list',

    initialize: function(){
        this.render();
    },

    render: function(){
            this.collection.each(function(model){
            this.addOne(model);
        }, this);
    },

    //create an itemview for a model, and add it to the list view
    addOne:function(model){
        var itemView = new ItemView({model: model});
        this.$el.append(itemView.render().el);
    }
});
Run Code Online (Sandbox Code Playgroud)

Her*_*ran 5

this.collection.each可以和Backbone一起使用,问题是你没有将实际的Backbone集合传递给ItemView的实例,而只是一个数组.您需要以下内容:

var itemsCollection = new ItemsCollection(items), // substitute your collection variable
    itemsCollectionView = new ListView({ collection: itemsCollection });
Run Code Online (Sandbox Code Playgroud)

此外,我尝试在Backbone 1.0.0和jQuery 1.10.1上运行您的代码,我得到了

   TypeError: Object [object Array] has no method 'each'
Run Code Online (Sandbox Code Playgroud)