"this.collection.each不是函数;.应该'它不是简单地说“;每个”;

"this.collection.each is not a function". Shouldn't it simply say "each"?

本文关键字:简单 每个 函数 this quot collection each 应该      更新时间:2023-09-26

我真的有一个由两部分组成的问题。

控制台告诉我:"类型错误:this.collection.each不是函数"

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

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

附言:我已经确认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);
    }
});

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

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

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

   TypeError: Object [object Array] has no method 'each'