Skip to content

Instantly share code, notes, and snippets.

@rstuven
Last active July 12, 2017 23:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstuven/65c782ac004a4da8bb9a to your computer and use it in GitHub Desktop.
Save rstuven/65c782ac004a4da8bb9a to your computer and use it in GitHub Desktop.
Decorators in CoffeeScript
###
`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
@rstuven
Copy link
Author

rstuven commented Jul 29, 2015

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