事件發射器

當事件觸發(這意味著與釋出事件發出事件相同)時,將同步呼叫每個偵聽器( )以及傳遞給 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()