Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Backbone.js how can I get Model superclass defaults to act as defaults for subclasses?

I have a class that defines some defaults, and a subclass that defines some defaults. But when I create an instance of the subclass it only looks at the local defaults and does not merge its defaults with those of the parent. Is there any simple way to do this without explicitly merging the local defaults with the parent defaults in the initialize function of every subclass?

var Inventory = Backbone.Model.extend({
    defaults: {
        cat: 3,
        dog: 5
    }
});

var ExtendedInventory = Inventory.extend({
    defaults: {
        rabbit: 25
    }
});

var ei = new ExtendedInventory({});
console.log(ei.attributes);

This outputs:

{rabbit: 25}

Not what I want:

{cat: 3, dog: 5, rabbit: 25}
like image 449
aw crud Avatar asked Jun 28 '11 11:06

aw crud


1 Answers

You can't do it like that. You will have to do it after the subclass

_.extend(ExtendedInventory.prototype.defaults, {rabbit: 25});

Put this after your model definition.

like image 53
Julien Avatar answered Sep 21 '22 15:09

Julien