Last active
December 27, 2015 20:09
-
-
Save darkoverlordofdata/7382016 to your computer and use it in GitHub Desktop.
Coffeescript Magic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Magic | |
# | |
# Dependency injection via prototype. | |
# | |
# | |
# Get all methods and properties in the prototype chain | |
# | |
metadata = (klass) -> | |
chain = [] | |
props = {} | |
proto = klass:: # starting point in the chain | |
# Build an inheritance list | |
until proto is Object:: | |
chain.push proto | |
proto = Object.getPrototypeOf(proto) | |
# Reverse list to process overrides in the correct order | |
for proto in chain.reverse() | |
if proto isnt Object:: | |
# Build the inherited properties table | |
for key in Object.getOwnPropertyNames(proto) | |
props[key] = Object.getOwnPropertyDescriptor(proto, key) | |
props | |
magic = (parent, klass, args...) -> | |
# clone the object with all properties | |
child = Object.create(parent, metadata(klass)) | |
# call the constructor | |
klass.apply child, args | |
child | |
# | |
# Main Controller Class | |
# | |
class Controller | |
constructor: -> | |
@date = new Date() | |
@user = magic(@, Model, 'Zaphod') | |
println: (msg) -> | |
console.log msg | |
# | |
# | |
# | |
class Model | |
constructor: (name) -> | |
@name = name | |
hello: () -> | |
@println @name + " " + @date | |
# | |
# Create the applications main controller | |
# | |
controller = new Controller() | |
# | |
# Call the models hello method. | |
# Missing methods and properties fallback to the controller. | |
# | |
controller.user.hello() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment