-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2020-03-16 实现简易版 EventEmitter #10
Comments
class EventEmitter {
constructor() {
this.evePool = [];
}
on(e, cb) {
if (!this.evePool[e]) this.evePool[e] = [];
this.evePool[e].push(cb);
}
once(e, cb) {
if (!this.evePool[e]) this.evePool[e] = [];
const fn = (...args) => {
cb(...args);
this.evePool[e] = this.evePool[e].filter(f => f !== fn);
}
this.evePool[e].push(fn);
}
emit(e, ...args) {
if (this.evePool[e])
this.evePool[e].forEach(cb => {
cb(...args);
});
}
} |
class EventEmitter {
constructor() {
this.events = Object.create(null);
}
on(key, handler) {
(this.events[key] || (this.events[key] = [])).push(handler);
}
once(key, handler) {
const _handler = (...args) => {
handler(...args);
this.off(key, _handler)
}
(this.events[key] || (this.events[key] = [])).push(_handler);
}
off(key, handler) {
const events = this.events[key];
if (events) {
this.events[key] = events.filter(h => h !== handler);
}
}
emit(key, ...args) {
const _events = this.events[key];
if (_events) {
_events.forEach(h => h(...args));
}
}
} |
class EventEmitter{
_cache = {}
_onceCache = {}
on(key, callback){
const events = this._cache[key] = this._cache[key]?.length ? this._cache[key] : []
events.push(callback)
}
once(key, callback){
const events = this._onceCache[key] = this._onceCache[key]?.length ? this._onceCache[key] : []
events.push(callback)
}
emit(key, ...args){
this._cache[key].forEach(event => event(...args))
this._onceCache[key]?.length && this._onceCache[key].forEach(event => event(...args))
this._onceCache[key] = []
}
} |
class EventEmitter {
constructor() {
this.events = []
}
on(ev, callback) {
if (!this.events[ev]) this.events[ev] = []
this.events[ev].push(callback)
}
once(ev, callback) {
// 执行完解除绑定(包装处理)
const wrapCb = (...args) => {
callback.apply(null, args)
this.off(ev, wrapCb)
}
this.on(ev, wrapCb)
}
off(ev, callback) {
this.events[ev] = this.events[ev] && this.events[ev].filter(fn => fn !== callback)
}
emit(ev, ...args) {
this.events[ev] && this.events[ev].forEach(fn => fn.apply(null, args))
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: