nodejs 基础模块 events

字数 58阅读 46

events 文档

events

绑定事件用 on,触发事件用 emit

image

例子

image
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);
image

传入参数,

定义报出错误的例子

image
const EventEmitter = require('events');

class CustomEvent extends EventEmitter {
}

const ce = new CustomEvent();

ce.on('test', () => {
  console.log('this is a test!');
});

ce.emit('test');

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

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

传多个参数

image

只触发一次

once 只触发一次

image
const EventEmitter = require('events');

class CustomEvent extends EventEmitter {
}

const ce = new CustomEvent();

ce.once('once', () => {
  console.log('This is test once');
});

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

移除事件

removeListener 移除事件

image
const EventEmitter = require('events');

class CustomEvent extends EventEmitter {
}

const ce = new CustomEvent();

ce.on('test', fn1);
ce.on('test', fn2);

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

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

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

setTimeout(() => {
  ce.removeListener('test', fn1);
  ce.removeListener('test', fn2);
}, 1500);
image

推荐阅读更多精彩内容