Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created March 7, 2012 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lancejpollard/1996756 to your computer and use it in GitHub Desktop.
Save lancejpollard/1996756 to your computer and use it in GitHub Desktop.
Use cases for the `extended` hook in CoffeeScript

The extended hook in CoffeeScript

List of Use Cases

  1. To track subclasses
  2. To reinitialize class-level variables in a subclass that were defined in a parent class.
  3. To have control over what happens when something is subclassed

These are the ones off the top of my head, more use cases are elaborated on here:

1. Tracking Subclasses

class Model

class Parent extends Model

class Child extends Parent

Model.subclasses #=> [Parent, Child]

This makes metaprogramming possible. For one example, I can track dependencies, so if a file changes, and it has dependent subclasses, I can reload them in node.js. Another, I can automatically validate that a type property is valid given a model when it's saved, b/c we know all possible subclasses. Plus, in Ruby/Rails, there's a million places you have an included or extended hook where being able to store metadata about this relationship gives you a lot of power.

2. Reinitialize Class Variables

class Attribute
  constructor: (name, options = {}) ->
    @name    = name
    @options = options

class Model
  @attributes: {}
  @attribute: (name, options) ->
    @attributes[name] = new Attribute(name, options)

class Parent extends Model
  @attribute "role", default: "guest"

class Child extends Parent

# I don't want this to happen:
Child.attributes.role.options.customProperty = true
console.log Parent.attributes.role.options
# {"default":"guest","customProperty":true}

# instead, I want to clone all `attributes` in the subclass,
# i.e. I want to clone all class-level objects in the subclass

3. To have control over what happens when something is subclassed

Ember.js has a more robust implementation of extend, where it properly adds mixins and such to the subclass. Just being able to do this would open up a ton of possibilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment