Reputation: 21
I am receiving the following message when I try to use Backbone's collection.each() method:
TypeError: Object function (){ return parent.apply(this, arguments); } has no method 'each'.
I'm learning Backbone from some Jeffrey Way tutorials; I entered identical code to his, but for some reason it doesn't work.
var Person = Backbone.Model.extend({
defaults: {
name: 'besim dauti',
age: 15,
occupation: 'web developer'
}
});
var PeopleView = Backbone.View.extend({
tagName: 'ul',
render: function(){
this.collection.each(function(person) {
var personView = new PersonView({ model: person });
this.$el.append(personView.render().el)
}, this)
return this;
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#personTemplate').html() ),
render: function(){
this.$el.html(this.template(this.model.toJSON()) );
return this;
}
});
var PeopleCollection = Backbone.Collection.extend({
model: Person
});
var peopleCollection = new PeopleCollection([
{
name: 'besim',
age: 25,
occupation: 'web developer'
},
{
name: 'gaurav',
age: 25,
occupation: 'web designer'
},
{
name: 'jeffry',
age: 27
}
])
var peopleView = new PeopleView ({collection: PeopleCollection});
$(document.body).append(peopleView.render().el);
Why is there this problem with the .each()
function? I typed the code identically and, for Jeffrey, it worked as expected, but for me it displayed this error. I appreciate your help.
Upvotes: 2
Views: 18560
Reputation: 3684
Your code works fine in jsfiddle.
http://jsfiddle.net/puleos/kbLES/
var peopleView = new PeopleView ({collection: peopleCollection});
$(document.body).append(peopleView.render().el);
It looks like you may have a dependency issue. Can you post how you are including your scripts on the page?
Upvotes: 1
Reputation: 13476
You need to initialise the PeopleCollection
.
See: var peopleView = new PeopleView ({collection: PeopleCollection});
You are passing in the raw constructor and not an instance of it.
You should do this:
var peopleCollection = new PeopleCollection(); // Create an instance of PeopleCollection
var peopleView = new PeopleView ({collection: peopleCollection}); // Pass it to peopleView
If you are familiar with OOP (Object orientated programming) think of PeopleCollection
as a class and var peopleCollection = new PeopleCollection()
as an instance of that class. You must work with instances.
You will also encounter an error inside your .each
because you capitalised person
. Change to:
this.collection.each(function(person) {
var personView = new PersonView({ model: person });
this.$el.append(personView.render().el)
}, this)
Upvotes: 5