Backbone.js Collection fetch () throws Uncaught TypeError: Cannot read the 'IDAttribute' property from undefined

I am trying to learn Backbone.js

He worked on GET, PUT and DELETE for one model. But when I create the collection, the fetch method gives this error: Uncaught TypeError: Cannot read the 'idAttribute' property from undefined (backbone.js: 683)

Here is the code I'm trying to do:

Person = Backbone.Model.extend({ urlRoot: '/people' }); PersonList = Backbone.Collection.extend({ model: 'Person', url: '/people' }); var personList = new PersonList(); personList.fetch(); 

When retrieving, the server returns the following JSON, which, in my opinion, 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?

+6
source share
2 answers

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

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

Here is the documentation for Collection-model .

+10
source

In addition to @fbynite's answer.

You must also ensure that the object you are referencing is a valid base model (an object that has been extended from Backbone.Model ).

Therefore, when invoking the js files of the / collection / view model, make sure that the model files were called earlier than the collection files.

In my example, I spent hours studying, and my problem was initiating the collection before the model, so I suggest not using the line: App.AppModel = App.AppModel || {}; App.AppModel = App.AppModel || {}; App.AppModel = App.AppModel || {}; It is less โ€œsafe,โ€ but itโ€™s better to let the code break so you can see whatโ€™s wrong.

 window.App = window.App || {}; App.AppModel = App.AppModel || {}; //DO not use this line!! App.AppCollection = Backbone.Collection.extend({ model: App.AppModel, }); 
0
source

All Articles