Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Backbone Model and keep defaults while using Coffeescript

Given I have the following inheritance in coffeescript.

I get an error because "mammal" seems to be undefined for myCat.

I read in some other post that I would actually have to make defaults a function to inherit the default values. But how do 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'))
like image 285
laberning Avatar asked Jul 27 '26 12:07

laberning


1 Answers

The easiest thing would be to use functions for both defaults, then your Cat can simply 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 could keep the non-function defaults in Animal but that would get ugly so don't bother.

Note that _.extend alters its first argument so usually you want to say things like _({}).extend(...) to avoid scribbling on things that you don't own. In this case, you know that Animal#defaults returns a brand new object every time it is called so you don't have to worry about that. If you're paranoid, you could do this instead:

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

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

like image 162
mu is too short Avatar answered Jul 29 '26 09:07

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!