从* class *构造函数发出的Catch事件

时间:2014-03-23 15:38:28

标签: javascript node.js events event-handling coffeescript

是否可以捕获从 class 构造函数发出的事件?问题是它在附加处理程序之前触发。 CoffeeScript中的类代码:

class YtVideo extends events.EventEmitter
    constructor: ->
            events.EventEmitter.call this
            # logic
            @emit 'error', 'Invalid YouTube link.'

示例:

ytVideo = new YtVideo

ytVideo.on 'error', (e) -> # This doesn't work for events from constructor.
    alert e

1 个答案:

答案 0 :(得分:0)

简单的答案是,正如您所看到的,您是否无法在构造函数中同步触发'error',因为您还没有时间绑定错误事件处理程序。

鉴于此,您有两种选择:

1。抛出并捕获正常异常

throw 'Invalid YouTube link.'

try
  ytVideo = new YtVideo
catch e
  alert e

2。延迟错误事件,以便您有时间绑定错误侦听器

process.nextTick =>
  @emit 'error', 'Invalid YouTube link.'
相关问题