是否可以捕获从 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
答案 0 :(得分:0)
简单的答案是,正如您所看到的,您是否无法在构造函数中同步触发'error'
,因为您还没有时间绑定错误事件处理程序。
鉴于此,您有两种选择:
throw 'Invalid YouTube link.'
和
try
ytVideo = new YtVideo
catch e
alert e
process.nextTick =>
@emit 'error', 'Invalid YouTube link.'