“Uncaught TypeError: undefined is not a function”

2019-03-25 19:51发布

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?

标签: backbone.js
2条回答
祖国的老花朵
2楼-- · 2019-03-25 20:11

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

查看更多
混吃等死
3楼-- · 2019-03-25 20:16

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

查看更多
登录 后发表回答