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', '书');