Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Uncaught TypeError: undefined is not a function" initializing Backbone collection

Tags:

backbone.js

I have a Backbone collection something like the following:

var FooCollection = Backbone.Collection.extend({
    model:Foo,

    initialize: function (attributes, options) {
        this.barId = options.barId;
    }
});

var Foo = Backbone.Model.extend({});

When I try to initialize this, I get "Uncaught TypeError: undefined is not a function" in the _prepareModel() function of Backbone.Collection.

The bad call is in model = new this.model(attrs, options).

// Prepare a model or hash of attributes to be added to this collection.
_prepareModel: function(model, options) {
  options || (options = {});
  if (!(model instanceof Model)) {
    var attrs = model;
    options.collection = this;
    model = new this.model(attrs, options); // <-- BLOWS UP HERE
    if (!model._validate(model.attributes, options)) model = false;
  } else if (!model.collection) {
    model.collection = this;
  }
  return model;
},

When I step through _prepareModel() in the debugger, it looks like the type of this at that point is child, and this.model is, in fact, undefined.

Can anyone tell me what I'm doing wrong?

like image 770
David Moles Avatar asked Jan 04 '13 18:01

David Moles


2 Answers

In my actual code Foo was declared after FooCollection. Didn't realize that Javascript doesn't support forward declarations. [headdesk]

like image 162
David Moles Avatar answered Oct 07 '22 00:10

David Moles


I was experiencing the same problem. My problem was I had included my Model script after Collection Script:

<script src="scripts/collections/Classes.js"></script>
<script src="scripts/models/Class.js"></script>

To fix it I just had to move the Class.js up above Classes.js:

<script src="scripts/models/Class.js"></script>
<script src="scripts/collections/Classes.js"></script>

Cheers

like image 36
Madclouds Avatar answered Oct 06 '22 23:10

Madclouds