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?
In my actual code Foo
was declared after FooCollection
. Didn't realize that Javascript doesn't support forward declarations. [headdesk]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With