我真的有一个由两部分组成的问题。
控制台告诉我:"类型错误: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'