Dol
Dol

Reputation: 964

Dynamic callback in Javascript

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“

Upvotes: 0

Views: 112

Answers (1)

elclanrs
elclanrs

Reputation: 94131

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

Upvotes: 3

Related Questions