观察者模式
addEventListener
removeEventListener

Event.js

  1. const { EventEmitter } = require('events');
  2. class Event extends EventEmitter {
  3. constructor() {
  4. super();
  5. setInterval(() => {
  6. this.emit('change', { price: Math.random() * 100})
  7. }, 2000)
  8. }
  9. }
  10. // 把底层的逻辑封装起来,
  11. module.exports = Event;

index.js

  1. const Event = require('./lib');
  2. const jim = new Event();
  3. jim.addListener('change', (res) => {
  4. if(res.price <= 80) {
  5. console.log('haha', res.price)
  6. }
  7. })

setMaxListeners

EventEmitter如果添加了过多的监听器,Node.js觉得你有内存泄漏嫌疑,会抛出一个warning

  1. setTimeout(() => {
  2. // geektime.setMaxListeners(200); 消除 warningn
  3. for (let i = 0; i < 100; i++) {
  4. event.on('channge', ({ res }) => {
  5. })
  6. }
  7. }, 10000)