NodeJS基础入门-Event

大多数Node.js核心API都采用惯用的异步事件驱动架构,其中某些类型的对象(触发器)会周期性地触发命名事件来调用函数对象(监听器)。
例如,net.Server对象会在每次有新连接时触发事件;fs.ReadStream会在文件被打开时触发事件;流对象会在数据可读时触发事件。
所有能触发事件的对象都是EventEmitter类的实例。eventEmitterr.on()函数,允许将一个或多个函数绑定到会被对象触发的命名事件上。事件名称通常是驼峰式的字符串,但也可以使用任何有效的JavaScript属性名。
当EventEmitter对象触发一个事件时,所有绑定在该事件上的函数都被同步地调用。监听器的返回值会被丢弃。
例子,一个绑定了一个监听器的EventEmitterr实例。eventEmitter.on()方法用于注册监听器,eventEmitter.emit()方法用于触发事件。

const EventEmitter = require('events');

class CustomEvent extends EventEmitter { 

}

const ce = new CustomEvent();
ce.on('test', ()=>{
  console.log('This is a test!')
});

setInterval(() => {
  ce.emit('test')
},500);

不停的触发这个事件:

This is a test!
This is a test!
This is a test!
This is a test!
This is a test!
This is a test!
This is a test!
This is a test!
^C

Error错误信息打印

const EventEmitter = require('events');

class CustomEvent extends EventEmitter { 

}

const ce = new CustomEvent();
ce.on('error', err =>{
  console.log(err)
});

ce.emit('error',new Error('oops!'));

Error: oops!
at Object.

监听并触发结果,只调用一次

const EventEmitter = require('events');

class CustomEvent extends EventEmitter { 

}
// 只调用一次
const ce = new CustomEvent();
ce.once('test', () =>{
  console.log('test event');
});

setInterval(() => {
    ce.emit('test')
  }, 500);

test event

移除事件:


class CustomEvent extends EventEmitter {}

function fn1() {
  console.log('fn1');
}
function fn2() {
  console.log('fn2')
}

const ce = new CustomEvent();
ce.on('test', fn1);    //可以绑定多个方法
ce.on('test', fn2);

setInterval(() => {
  ce.emit('test');  
},500);

setTimeout(() => {
  //  ce.removeListener('test',fn2);  //移除fn2

  ce.removeAllListeners('test');    //移除所有事件
}, 2000);

fn1
fn2
fn1
fn2
fn1
fn2
^C

猜你喜欢

转载自www.cnblogs.com/carious/p/10095555.html