初探 node events模块

模块概述

在 node 中 events模块是核心模块之一, 几乎所有常用的 node 模块都继承了 events模块

例如,net.Server 会在每次有新连接时触发事件,fs.ReadStream 会在打开文件时触发事件,stream会在数据可读时触发事件等

events模块本身非常简单,从官网文档中我们发现该模块的API虽然很多,但是我们常用的也就那几个,下面我们来看一下几个简单例子

例子

例子1:单个事件监听
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!
例子2:同个事件,多个事件监听
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

从上面我们可以看到,事件触发时,事件监听器按照注册的顺序依次执行

例子3:只运行一次的事件监听
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
例子4: 注册时间监听器前,事件先触发
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

从上面例子中我们可以看到,注册时间监听器前,事件先触发,则该事件会直接被忽略

例子5:执行顺序
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
例子6:移出事件监听
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

你可能感兴趣的:(node.js,javascript)