Javascript中的动态回调

时间:2015-03-05 23:27:47

标签: javascript coffeescript

是否可以动态地向函数/ coffeescript类中封装的每个函数添加回调?与after_filter中的rails一样。

例如:

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“

1 个答案:

答案 0 :(得分:3)

作为一项功能,这不存在,但您可以创建一个装饰器,您可以手动应用于原型中的每个功能:

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

通过一些抽象,你可以将它重用于其他类,但仍然有点手动:

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