NodeJS事件循环

## 基本模型

“`javascript
const events = require(‘events’);
const eventEmitter = new events.EventEmitter();

function sayHi() {
console.log(‘hi.’);
}

// 绑定监听 see 事件的处理函数 sayHi
eventEmitter.on(‘see’, sayHi);

// 触发 see 事件
eventEmitter.emit(‘see’);
“`

## 进一步编程

“`javascript
const events = require(‘events’);
const eventEmitter = new events.EventEmitter();

function toCode() {
let timer = {};

console.log(‘I\’m coding…’);

timer = setTimeout(() => {
eventEmitter.emit(‘tired’);
clearTimeout(timer);
}, 3000);
}

function toRest() {
console.log(‘I have to rest.’);
}

eventEmitter.on(‘boring’, toCode);
eventEmitter.on(‘tired’, toRest);

eventEmitter.emit(‘boring’);
“`

Advertisements