Created
December 31, 2014 17:21
-
-
Save keithnorm/8b7496eb2dd5c23c62d5 to your computer and use it in GitHub Desktop.
A JavaScript implementation of the Rails delegate class method (kind of)
This file contains 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
class Delegator | |
@delegate: [] | |
constructor: -> | |
for delegate in @constructor.delegate | |
target = delegate[delegate.length - 1].to | |
for attribute in delegate when not attribute.to | |
property = {} | |
if /\(\)$/.test attribute | |
funcName = attribute.substring 0, attribute.length - 2 | |
@[funcName] = (-> | |
_funcName = funcName | |
-> | |
@[target][_funcName]() | |
)() | |
else | |
property[attribute] = | |
get: (-> | |
name = attribute | |
-> | |
@[target][name] | |
)() | |
Object.defineProperties @, property |
This file contains 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
class MyThing extends Delegator | |
@delegate: [ | |
['foo', to: 'bar'] | |
] | |
constructor: (@bar) -> | |
super | |
bar = {foo: 'foobar'} | |
myThing = new MyThing(bar) | |
myThing.foo # 'foobar' | |
# Anyway, that's the idea of it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment