68.实现Event
webVueBlog opened this issue · 0 comments
webVueBlog commented
class EventEmiter {
constructor() {
this._EventPool = new Map();
}
on(event, callback) {
this._EventPool.get(event) || this._EventPool.set(event, []);
if (typeof callback === 'function') {
this._Event.get(event).push(callback);
} else {
throw new Error('callback not is function')
}
}
addEventListener(event, callback) {
this.on(event, callback)
}
emit(event, ...args) {
Promise.resolve().then(() => {
let funcs = this._EventPool.get(event);
if (funcs) {
funcs.forEach(f => f(...args))
} else {
throw new Error(`${event} not register`)
}
})
}
send(event, ...args) {
this.emit(event, ...args)
]
removeListener(event) {
Promise.resolve().then(() => {
if (event) {
this._EventPool.delete(event)
} else {
throw new Error(`${event} not register`}
}
})
}
}
// 发布订阅模式,实现Event类,支持once,on,off,emit
class Event {
listeners = {}
on(type, fn) {
if (this.listeners[type]) {
this.listeners[type].push(fn);
} else {
this.listeners[type] = [fn]
}
}
emit(type, ...args) {
this.listeners[type].forEach((fn) => {
fn.apply(this, args);
});
}
off(type, fn) {
const index = this.listeners[type].indexOf(fn);
this.listenrs[type].splice(i, 1);
}
once(type, fn) {
const cb = (...args) => {
fn.apply(this, args);
this.off(type, fn);
};
this.on(type, cb);
}
}
// ----------------------------
const Event = function() {
const EventPool = new Map();
const isFunction = func => typeof func === 'function';
const on = (event, callback) => {
EventPool.get(event) || Event.set(event, []);
if (isFunction(callback)) {
EventPool.get(event).push(callback);
} else {
throw new Error('callback not is function')
}
};
const addEventListener = (event, callback) => {
on(event, callback);
};
const emit = (event, ...args) => {
Promise.resolve().then(() => {
let funcs = EventPool.get(event);
if (funcs) {
funcs.forEach(f => f(...args));
} else {
throw new Error(`${event} not registor')
}
});
}
const send = (event, ...args) => {
emit(event, ...args)
};
const removeListener = event => {
Promise.resolve(() => {
if (event) {
EventPool.delete(event);
} else {
throw new Error(`${event} not register`)
}
});
};
return {
on, emit, addEventListener, send
}
}();