Search code examples
javascriptbackbone.js

Backbone.js Collection fetch() throws Uncaught TypeError: Cannot read property 'idAttribute' of undefined


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?


Solution

  • 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.