带有Coffee SubClass问题的EventEmitter

时间:2013-01-16 04:21:09

标签: javascript node.js coffeescript

我不确定为什么这不起作用。有人能告诉我吗?我没有看到任何事件被记录,但它们确实得到emitted ......好吧,我认为:)

{EventEmitter} = require 'events'

class Base extends EventEmitter

class App extends Base

  constructor: (cb) ->

    console.log 'setup'

    @on 'listener:1', (data) ->
      console.log 'listener 1: ' + data

    @on 'listener:2', (data) ->
      console.log 'listener 2: ' + data

    cb()

class One extends Base

  fire: () ->

    console.log 'fire 1'

    @emit 'listener:1', 1

class Two extends Base

  fire: () ->

    console.log 'fire 2'

    @emit 'listener:2', 2

new App(
  () ->
    setTimeout (->
      one = new One()
      one.fire()
      setTimeout (->
        two = new Two()
        two.fire()
      ), 2000
    ), 2000
)

1 个答案:

答案 0 :(得分:1)

该计划的产出符合预期;只有App会自行设置侦听器,但它永远不会emit任何内容(仅OneTwo,这些不是 App的子句1}},这样做)。也许你正在寻找更像以下的东西?

{EventEmitter} = require 'events'

class Base extends EventEmitter
  constructor: ->
    console.log 'setup'

    @on 'listener:1', (data) ->
      console.log 'listener 1: ' + data

    @on 'listener:2', (data) ->
      console.log 'listener 2: ' + data

class App extends Base
  constructor: (cb) ->
    super()
    cb()

class One extends Base
  fire: ->
    console.log 'fire 1'
    @emit 'listener:1', 1

class Two extends Base
  fire: ->
    console.log 'fire 2'
    @emit 'listener:2', 2

new App(
  ->
    setTimeout (->
      one = new One()
      one.fire()
      setTimeout (->
        two = new Two()
        two.fire()
      ), 2000
    ), 2000
)