Corbee
Corbee

Reputation: 1009

Backbone collection.fetch() causing TypeError: this.model is undefined

everything seems correct, but whenever I do the following, I get TypeError: f is undefined in backbone 1.1.2, Also, when I debug, I saw that it was able to receive the correct response, yet when I do categories.toJSON() I get nothing:

var categories = new App.Lookup.CategoryCollection();
categories.url = 'index.php?r=lookupapi/categories';
categories.fetch();

App.Lookup.CategoryCollection = Backbone.Collection.extend({
    model: App.Lookup.CategoryModel                
});

App.Lookup.CategoryModel = Backbone.Model.extend({

});

What am I doing wrong here?

Update:

I use the development version as suggested by user972 and got the following error message:

TypeError: this.model is undefined

categories.fetch() is the one causing the error, it pointed to this function in backbone:

 // Define how to uniquely identify models in the collection.
    modelId: function (attrs) {
      return attrs[this.model.prototype.idAttribute || 'id'];
    },

But I still couldn't figure out why it is undefined.

Upvotes: 1

Views: 803

Answers (2)

fbynite
fbynite

Reputation: 2661

The declaration of App.Lookup.CategoryModel is not hoisted above App.Lookup.CategoryCollection. You need to define App.Lookup.CategoryModel before you use it.

So change your code to:

App.Lookup.CategoryModel = Backbone.Model.extend();

App.Lookup.CategoryCollection = Backbone.Collection.extend({
  model: App.Lookup.CategoryModel                
});

var categories = new App.Lookup.CategoryCollection();
categories.url = 'index.php?r=lookupapi/categories';
categories.fetch();

In response to:

I saw that it was able to receive the correct response, yet when I do      
categories.toJSON() I get nothing

If you want to see the results of fetch you need to pass a success callback:

categories.fetch({
   success: function(collection, response, options) {
      console.log(collection.toJSON());
   }
});

Upvotes: 1

Ash
Ash

Reputation: 2595

Just out of curiosity, have you referenced the script files in the proper order? It seems more of from script loading error than the code based.

<script src="underscore-1.6.0-min.js"></script>
<script src="backbone-1.1.2-min.js"></script>

Other thing that might be of help is to use non-min version of backbone and try locating where it is crashing and why?

 <script src="http://backbonejs.org/backbone.js"></script>

Upvotes: 0

Related Questions