Skip to content

dbrans/coffeeclass

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

# DSL for creating and extending classes and mixins in coffeescript


# Create a class
# Initialize properties on a per-instance basis using functions
# Here, every instance of A will have its own queue.
class A extends Class
  @initialize
    queue: Array # or -> []
    map: Object # or -> {}

a1 = new A
a1.queue.push 'foo'
(new A).queue # empty

# Use @introduce when you intend to declare new keys
# Here, an exception is thrown since 'queue' was introduced in A
class B extends A
  @introduce
    queue: ->
    bar: ->

# init method is called immediately after object construction with the arguments
# that were passed to the constructor:
class C extends B
  init: (arg) ->


# Use @before and @after to do most of your method 'overriding'.
# The super (or whatever was at that key) is called for you, whether it exists or not.
class D extends C
  @after init: (arg) ->



# Define a mixin
QueueMixin = ->
  @initialize
    queue: Array
  @introduce push: (x) -> @queue.push x

# Extend a mixin
StackMixin = ->
  @do QueueMixin
  @introduce pop: -> @queue.pop()

OtherMixin = ->

class MyStack extends Class
  @do StackMixin, OtherMixin #Apply mixins

# Other nice stuff: Properties, Delegation, Object.do

# Properties
class Point extends Class
  @property
    x:
      get: -> @_x ?= 0
      set: (@_x) ->
    y:
      get: -> @_y ?= 0
      set: (@_y) ->

p = new Point
p.x() # -1
p.x 3
p.x() # 3


# Delegation
class Rect extends Class
  @initialize
    topleft: -> new Point
    dim: -> new Point
  @delegate x: 'topleft', y: 'topleft'
  @delegate width: 'dim.x', height: 'dim.y'


# Object.do
# Descendents of Class implement 'do', a safe form of 'with'
r = new Rect
r.do ->
  @x 3
  @width 15
  @dim.do ->
    @y 15

About

DSL for creating classes and mixins for coffeescript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published