nodejs核心模块 events 实现

events 实现

events.js

function EventEmitter() {
  this.events = {};//会把所有的事件监听函数放在这个对象保存
  this._maxListeners = 10;
}

EventEmitter.prototype.setMaxListeners = function (num) {
  this._maxListeners = num;
};
EventEmitter.prototype.listeners = function (type) {
  return this.events[type] || [];
};
/*给指定的事件绑定事件的处理函数,1参数是事件类型,2参数是事件监听函数*/
EventEmitter.prototype.on = EventEmitter.prototype.addListener = function (
  type, listener) {
  if (this.events[type]) {
    if (this.events[type].length > this._maxListeners && this._maxListeners !=
      0) {
      console.error(
        `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${this.events[type].length} ${type} listeners added. Use emitter.setMaxListeners() to increase limit`,
      );
    }
    this.events[type].push(listener);
  } else {
    this.events[type] = [ listener ];
  }
};
EventEmitter.prototype.once = function (type, listener) {
  function wrapper(...rest) {
    listener.apply(this, rest);
    this.removeListener(type, wrapper);
  }

  this.on(type, wrapper);
};
EventEmitter.prototype.removeListener = function (type, listener) {
  if (this.events[type]) {
    this.events[type] = this.events[type].filter(l => l != listener);
  }
};
//移除某个事件的全部监听函数
EventEmitter.prototype.removeAllListeners = function (type) {
  if (this.events[type]) {
    this.events[type] = [];
  }
};
EventEmitter.prototype.emit = function (type, ...rest) {
  this.events[type] &&
  this.events[type].forEach(listener => listener.apply(this, rest));
};
module.exports = EventEmitter;

demo.js

/*
* events
* 在node里面,node是基于事件驱动的
* */

let EventEmitter = require('./events');

let util = require('util');

/*这是一个类*/
function Bell() {
  EventEmitter.call(this);//继承私有属性
}

//进行原型继承 继承公有方法
util.inherits(Bell, EventEmitter);

let bell = new Bell();

function studentInClassroom(roomNumber, things) {
  console.log(`学生带着${things}${roomNumber}教室`);
}

function teacherInClassroom(roomNumber, things) {
  console.log(`老师带着${things}${roomNumber}教室`);
}

function masterInClassroom(roomNumber, things) {
  console.log(`耿老师带着${things}${roomNumber}教室`);

}

bell.setMaxListeners(5);
bell.addListener('响', studentInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.on('响', teacherInClassroom);
bell.once('响', masterInClassroom);
bell.emit('响', '301', '书');
console.log('======');
bell.emit('响', '301', '书');




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值