Last active
July 12, 2017 23:15
-
-
Save rstuven/65c782ac004a4da8bb9a to your computer and use it in GitHub Desktop.
Decorators in CoffeeScript
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
### | |
`decorate` can apply decorators using the API proposed in | |
https://github.com/wycats/javascript-decorators | |
which is supported in Babel 5+ and TypeScript 1.5 | |
Usage: | |
Foo = decorate F("color"), G, class Foo | |
bar: decorate "bar", @, F("color"), G, -> | |
## or just... | |
decorate "bar", @, F("color"), G, -> | |
## ...if no tool misses explicit method declaration | |
Multiline declaration: | |
Foo = decorate [ | |
F "color" | |
G | |
H | |
I 123 | |
J | |
], class Foo | |
### | |
decorate = (decorators..., target) -> | |
# for easy multiline declaration | |
if decorators[0] instanceof Array | |
decorators = decorators[0] | |
if typeof decorators[0] is 'string' | |
# target is method | |
name = decorators.shift() | |
prototype = decorators.shift().prototype | |
descriptor = | |
value: target | |
writable: true | |
enumerable: true | |
configurable: true | |
for decorator in decorators | |
descriptor = decorator(prototype, name, descriptor) ? descriptor | |
Object.defineProperty prototype, name, descriptor | |
return prototype[name] | |
else | |
# target is class | |
for decorator in decorators | |
target = decorator(target) ? target | |
return target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://github.com/rstuven/es-decorate