6
votes

I am trying to learn Backbone.js

It had it working to GET, PUT and DELETE a single model. But, when I create a collection, the fetch method gives this error: Uncaught TypeError: Cannot read property 'idAttribute' of undefined (backbone.js:683)

Here is the code I am trying:

Person = Backbone.Model.extend({
    urlRoot: '/people'
});

PersonList = Backbone.Collection.extend({
    model: 'Person',
    url: '/people'
});

var personList = new PersonList();
personList.fetch();

On fetch, the server is returning the following JSON, which I think is correct:

[{"id":1,"name":"Matt","description":"Worker"},{"id":3,"name":"Test","description":"Test person"}]

I am using jQuery 2.0.3 (also tried 1.10.2), Underscore.js 1.5.2 and Backbone.js 1.1.0

What am I doing wrong?

2
For starters, model should reference a constructor not a string. Try model: Person when you extend the PersonList. - fbynite
@fbynite Thanks. I think that fixed it. If you made that an answer I would accept it... - user2736142

2 Answers

10
votes

When you extend a Backbone.Collection, model should be a reference to a constructor, not a string. So you need to remove the quotes from Person.

PersonList = Backbone.Collection.extend({
  model: Person,
  url: '/people'
});

Here is the documentation for Collection-model.

0
votes

In addition to @fbynite answer.

You also need to make sure the object you are referring to is a valid backbone model (object that has been extended from Backbone.Model).

So when calling the js files of model/collection/view make sure the model files has been called earlier than the collection files.

In my example, I've spent hours of investigation, and my problem was initiating the collection before the model, so I suggest not use the line of: App.AppModel = App.AppModel || {};. Its less "safer" but its better let the code break so you will be able to see whats wrong.

window.App = window.App || {};
App.AppModel = App.AppModel || {}; //DO not use this line!!

App.AppCollection = Backbone.Collection.extend({    
    model: App.AppModel,
});