事件发射器
当事件触发(这意味着与发布事件或发出事件相同)时,将同步调用每个侦听器( 源 )以及传递给 emit()
的任何附带数据,无论如何你传递的许多论点:
myDog.on('bark', (howLoud, howLong, howIntense) => {
// handle the event
})
myDog.emit('bark', 'loudly', '5 seconds long', 'fiercely')
将按照注册顺序调用侦听器:
myDog.on('urinate', () => console.log('My first thought was "Oh-no"'))
myDog.on('urinate', () => console.log('My second thought was "Not my lawn :)"'))
myDog.emit('urinate')
// The console.logs will happen in the right order because they were registered in that order.
但是如果你需要一个首先触发的监听器,在所有已经添加的其他监听器之前,你可以像这样使用 prependListener()
:
myDog.prependListener('urinate', () => console.log('This happens before my first and second thoughts, even though it was registered after them'))
如果你需要听一个事件,但你只想听一次,你可以使用 once
而不是 on
,或 prependOnceListener
而不是 prependListener
。触发事件并调用侦听器后,将自动删除侦听器,并且在下次触发事件时不会再次调用侦听器。
最后,如果你想删除所有的监听器并重新开始,请随意这样做:
myDog.removeAllListeners()