Skip to content Skip to sidebar Skip to footer

This Model Is Undefined When Trying To Add Object To Backbone Collection

I was wondering if there was anything I should keep in mind when using a backbone collection? I basically have a model, and my collection is defined as: LibraryPreps = (function (

Solution 1:

Have a look at LibraryPreps.prototype and you'll see where you're going wrong. First of all, your real code has to look more like this or you'll be getting ReferenceErrors:

varLibraryPreps = (function () { ... })();
varLibraryPrep  = (function () { ... })();

When the anonymous function which produces LibraryPreps executes, LibraryPrep will be undefined because it isn't assigned a value until later. If you do this:

varLibraryPreps = (function () {
    returnBackbone.Collection.extend({
        model: LibraryPrep,
        //...
    });
})();
varLibraryPrep = (function () {
    returnBackbone.Model.extend({ /*...*/ });
})();
console.log(LibraryPreps.prototype);

you'll see the LibraryPreps.prototype.model is undefined in the console. Demo: http://jsfiddle.net/ambiguous/y8cja/

The Backbone.Collection.extend call (with or without the anonymous self-executing function wrapper) is forcing the LibraryPrep to be evaluated when extend is called so you end up building a collection "class" with an undefinedmodel property. Then, inside Backbone, it will be looking for the idAttribute of the collection's model and you get your error.

Fix the order of your definitions so that things are defined before you use them:

varLibraryPrep  = (function () { ... })();
varLibraryPreps = (function () { ... })();

and you'll have better results.


As Loamhoof notes in the comments, your code works fine with the current version of Backbone (1.0.0) and I can't find this:

this._idAttr || (this._idAttr = this.model.prototype.idAttribute);

anywhere in the 1.0.0 source. Presumably you're using an older version of Backbone whose Collection#add method needs to know the idAttribute property of its model.

Solution 2:

Have you tried to add the models directly to the collection?

libPreps.add(libraries); 

http://backbonejs.org/#Collection-add

addcollection.add(models, [options]) Add a model (or an array of models) to the collection, firing an "add" event. If a model property is defined, you may also pass raw attributes objects, and have them be vivified as instances of the model. Pass {at: index} to splice the model into the collection at the specified index. If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true}, in which case their attributes will be merged into the corresponding models, firing any appropriate "change" events.

Post a Comment for "This Model Is Undefined When Trying To Add Object To Backbone Collection"