function EventEmitter() {
if(!this._events) {
this._events = {};
}
}
EventEmitter.prototype.addListener = function(type,fn) {//注册
if (!this._events){
this._events = {};
}
if(!this._events[type]) {
this._events[type] = fn;
}
};
EventEmitter.prototype.emit = function(type,...args) {//监听
let handler = this._events[type];
if(Array.isArray(handler)) {
for(var i = 0;i < length; i++) {
if(args.length > 0) {
handler[i].apply(this,args);
}else {
handler[i].call(this,args);
}
}
}else {
if(handler) {
if(args.length > 0) {
handler.apply(this,args);
}else {
handler.call(this,args);
}
}
}
return true;
};
EventEmitter.prototype.removeListener = function(type,fn) {//监听
let handler = this._events[type];
if(handler && typeof handler === 'function') {
delete this._events[type];
}else {
let pos;
for(let i = 0;i < handler.length; i ++) {
if(handler[i] === fn) {
pos = i;
}else {
pos = -1;
}
}
if(pos !== -1) {
handler.splice(pos,1);
}
}
};
EventEmitter.prototype.once = function(type,fn) {//监听
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
fn.apply(this, arguments);
}
}
g.fn = fn;
this.addListener(type, g);
return this;
};
var emitter = new EventEmitter();
var log = console.log;
emitter.once('bbb',log);
emitter.emit('bbb',1);
emitter.emit('bbb',2);
实现一个简单的emitter
最新推荐文章于 2024-09-06 16:38:31 发布