观察者模式
addEventListener
removeEventListener
Event.js
const { EventEmitter } = require('events');
class Event extends EventEmitter {
constructor() {
super();
setInterval(() => {
this.emit('change', { price: Math.random() * 100})
}, 2000)
}
}
// 把底层的逻辑封装起来,
module.exports = Event;
index.js
const Event = require('./lib');
const jim = new Event();
jim.addListener('change', (res) => {
if(res.price <= 80) {
console.log('haha', res.price)
}
})
setMaxListeners
EventEmitter如果添加了过多的监听器,Node.js觉得你有内存泄漏嫌疑,会抛出一个warning
setTimeout(() => {
// geektime.setMaxListeners(200); 消除 warningn
for (let i = 0; i < 100; i++) {
event.on('channge', ({ res }) => {
})
}
}, 10000)