0

Is it possible to dynamically add a callback to every function encapsulated within a function/coffeescript class? Like an after_filter in rails.

For example:

class Parent
  after_every_function_call_myCallback
  myCallback: ->
    console.log “callback called“

class Child extends Parent
  doSomething: ->
    console.log “a function“

class Regular 
  doSomething: ->
    console.log “a regular function“

> reg = new Regular()
> reg.doSomething()
< “a regular function“
> child = new Child()
> child.doSomething()
< “a function“
< “callback called“
5
  • Nop. You could create a decorator that you apply to every function manually, or you can loop prototype properties and extend the functions. But as a feature this doesn't exist. Commented Mar 5, 2015 at 23:34
  • How would I loop prototype properties? Can I keep them encapsulated? Commented Mar 5, 2015 at 23:38
  • 2
    for k, f of Child:: to loop, then you can Child::[k] = after Parent::myCallback, f, where after is a higher-order function that decorates another function. But again, it is manual, at least if you want to use Coffee classes Commented Mar 5, 2015 at 23:40
  • Interesting, do you think it could be done better another way, like without Coffee classes? Commented Mar 5, 2015 at 23:43
  • @elclanrs, if you put your comments into an answer I'll accept it because its a great solution and the right solution to this question. Commented Mar 6, 2015 at 9:41

1 Answer 1

3

As a feature this doesn't exist, but you could create a decorator that you apply to every function in the prototype manually:

after = (g, f) ->
  ->
    f()
    g()

class Parent
  myCallback: ->
    console.log 'callback called'

class Child extends Parent
  doSomething: ->
    console.log 'a function'

for k, f of Child::
  Child::[k] = after Parent::myCallback, f

child = new Child
child.doSomething()
# a function
# callback called

With a bit of abstraction you could reuse it for other classes, still a bit manual though:

decorate = (decor, f, clazz) ->
  for k, g of clazz::
    clazz::[k] = decor f, g
  clazz

class Child extends Parent
  doSomething: ->
    console.log 'a function'

decorate after, Parent::myCallback, Child
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.