On node events module

Module overview

In node, events module is one of the core modules. Almost all the common node modules inherit events module

For example, net.Server will trigger events every time there is a new connection, fs.ReadStream will trigger events when the file is opened, stream will trigger events when the data is readable, etc

The events module itself is very simple. From the official website documents, we find that although there are many APIs for this module, we use only those APIs. Let's take a look at a few simple examples

Example

Example 1: single event listening
let EventEmitter = require('events')
class Animal extends EventEmitter {}
let dog = new Animal()

dog.on('eat', function() {
  console.log('a dog eating food!')
})

dog.emit('eat')

// a dog eating food!
Example 2: the same event, multiple events listening
let EventEmitter = require('events')
class Animal extends EventEmitter {}
let dog = new Animal()
dog.on('eat', function(){
  console.log('a dog eating food')
})
dog.on('eat', function(){
  console.log('a dog eating')
})
dog.emit('eat')

// a dog eating food
// a dog eating

As we can see from the above, when an event is triggered, the event listener executes in the order of registration

Example 3: event listening that only runs once
let EventEmitter = require('events')
class Animal extends EventEmitter {}
let dog = new Animal()
dog.on('eat',function(){
  console.log('a dog eating food')
})
dog.once('eat',function(){
  console.log('a dog eating food once')
})
dog.emit('eat')
dog.emit('eat')

// a dog eating food
// a dog eating food once
// a dog eating food
Example 4: event triggered before registering time listener
let EventEmitter = require('events')
class Animal extends EventEmitter {}
let dog = new Animal()
dog.emit('eat',1)
dog.on('eat', function(index){
  console.log('a dog eating food-'+ index)
})
dog.emit('eat',2)
// a dog eating food-2

From the above example, we can see that if the event is triggered before registering the time listener, it will be ignored directly

Example 5: execution order
let EventEmitter = require('events')
class Animal extends EventEmitter {}
let dog = new Animal()
dog.on('eat', function(){
  console.log('a dog eating food1')
})
dog.emit('eat')
dog.on('eat', function(){
  console.log('a dog eating food2')
})
// a dog eating food1
// a dog eating food1
Example 6: remove event monitoring
let EventEmitter = require('events')
class Animal extends EventEmitter {}

function eat(){
 console.log('a dog eating food')
}
let dog = new Animal()
dog.on('eat', eat)
dog.emit('eat')
dog.removeListener('eat', eat)
// a dog eating food

Tags: Javascript

Posted on Mon, 04 Nov 2019 16:50:32 -0500 by etherboo