“Uncaught TypeError: undefined is not a function”

2019-03-25 20:10发布

问题:

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?

回答1:

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



回答2:

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



标签: backbone.js