How to extend base model and keep defaults when using Coffeescript

Considering I have the following inheritance in coffeescript.

I am getting an error because "mammal" looks like undefined for myCat.

I read in another post that I would actually need to use the default function to inherit the default values. But how can I do this with coffeescript?

class Animal extends Backbone.Model
  defaults:
    mammal: true

class Cat extends Animal
  defaults:
    furColor: "gray"

myCat = new Cat
alert(myCat.get('mammal'))

      

+3


source to share


1 answer


It's easiest to use functions for defaults

, then yours Cat

can just call super

and add a few things:

class Animal extends Backbone.Model
  defaults: ->
    mammal: true

class Cat extends Animal
  defaults: ->
    _(super()).extend(furColor: "gray")

      

You can keep the non-function defaults

in Animal

, but that would be terrible, so don't worry.



Note that it _.extend

changes its first argument, so usually you want to say things such as _({}).extend(...)

, to avoid jabbing things, 'city. In this case, you know that you Animal#defaults

return a new object every time it is called, so you don't need to worry about that. If you are paranoid, you can do this instead:

defaults: ->
  _({}).extend(super(), furColor: 'gray')

      

Demo: http://jsfiddle.net/ambiguous/LETAc/

+3


source







All Articles