1

With Backbone (1.2.3), I'm trying to build a collection using multiple models using the collection's model property:

var coll = Backbone.Collection.extend({
    model: function(attrs, options) {
        switch(attrs.type) {
            case 'type-a':
                return new BackboneModelA(attrs, options);
            case 'type-b':
                return new BackboneModelB(attrs, options);
        }
    },
    modelId: function(attrs) {
        return attrs.type + ':' + attrs.id;
    }
});

new coll([
    {type: 'type-a', id: 1}
]);

But it throws an error :

TypeError: Cannot read property 'type' of undefined(…)

Actually, modelId() is called twice and the second time, attrs is undefined.

PS: I know it's quite a duplicate of this : Backbone Collection with multiple models? but I haven't found anything helpful there.

Community
  • 1
  • 1
Menencia
  • 1,289
  • 1
  • 12
  • 23

1 Answers1

0

modelId is supported in 1.2.3.

The first time modelId is called, it's in the collection get function at line 969:

var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);

At that point, obj is {type: 'type-a', id: 1} and it is sent to modelId as-is.

The second time that modelId is called, it's in the collection _addReference function, at line 1126:

var id = this.modelId(model.attributes);

It means that at that point, model is not a Backbone model and that model.attributes is undefined.

Without the code of BackboneModelA, we won't be able to help you further, but you should look into it and make sure it extends Backbone.Model.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • Actually, `BackboneModelA` extends `Backbone.RelationalModel`. Do you think that's the reason it doesnt work ? – Menencia Sep 15 '16 at 07:25
  • @Menencia Out of the box, `Backbone.RelationalModel` works in this case. You should put a breakpoint in your `modelId` function and explore the stack trace checking if the `model.attributes` hash exist. – Emile Bergeron Sep 15 '16 at 14:52