class EventEmitter {
constructor(){
this.events = {};
}// 补全代码
on(event,fn){
if(Array.isArray(event)){
for(let i = 0; i < event.length; i++ ) {
this.on(event[i],fn);
}
}else {
(this.events[event] || (this.events[event] = [])).push(fn);
}
return this;
}
off(event,fn){
if(!event){
this.events = object.create(null);
return this
}
if(Array.isArray(event)){
for (let index = 0; index < event.length; index++) {
const element = event[index];
this.off(element,fn);
}
return this;
}else {
if(!fn){
this.events[event] = [];
return this;
}
const eventsList = this.events[event];
for (let index = eventsList.length - 1; index >= 0; index--) {
const element = eventsList[index];
if(fn === element ){
eventsList.splice(index,1);
}
}
}
}
emit(event){
if(!this.events[event]) return this;
const arg = Array.from(arguments).slice(1);
for(let i = 0; i < this.events[event].length;i++){
this.events[event][i](...arg);
}
}
}
//执行验证
(function (){
let sign1 = 0;
let sign2 = 0;
const emitter = new EventEmitter();
var fun1 = function() {sign1 ++};
var fun2 = function() {sign2 ++};
emitter.on('add',fun1 );
emitter.on('add',fun2);
emitter.off('add',fun1);
emitter.emit('add');
// emitter.emit('add');
const judge = sign1 === 0 && sign2 === 1;
console.log(judge,sign1,sign2,8)
})();
手写订阅发布
于 2022-05-18 13:24:10 首次发布
本文介绍了如何使用JavaScript实现一个EventEmitter类,包括on方法添加事件监听,off方法移除事件,以及emit方法触发事件。通过实例展示了如何动态绑定和解绑事件处理器,并在'add'事件上执行计数操作。
摘要由CSDN通过智能技术生成