events
绑定事件用 on
,触发事件用 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);
传入参数,
定义报出错误的例子
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!'));
传多个参数
只触发一次
once
只触发一次
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);
移除事件
removeListener
移除事件
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);