js实现一个EventEmitter类的完整写法
class EventEmitter {
constructor() {
this.listeners = new Map();
}
addListener(label, callback) {
this.listeners.has(label) || this.listeners.set(label, []);
this.listeners.get(label).push(callback);
}
removeListener(label, callback) {
let listeners = this.listeners.get(label);
let index;
if (listeners && listeners.length) {
index = listeners.reduce((i, listener, index) => {
return (isFunction(listener) && listener === callback) ? i = index : i;
}, -1);
}
if (index > -1) {
listeners.splice(index, 1);
this.listeners.set(label, listeners);
return true;
}
return false;
}
emit(label, ...args) {
let listeners = this.listeners.get(label);
if (listeners && listeners.length) {
listeners.forEach((listener) => {
listener(...args);
})
return true;
}
return false;
}
}
class Observer {
constructor(id, subject) {
this.id = id;
this.subject = subject;
}
on(label, callback) {
this.subject.addListener(label, callback);
}
}
通过on给被观察者对象绑定事件以及事件处理函数:
let observable = new EventEmitter();
let [observer1, observer2] = [
new Observer(1, observable),
new Observer(2, observable)
]
observer1.on('change', (data) => {
console.log(`${observer1.id} observered data:`, data);
})
observer2.on('haha', (data) => {
console.log(`${observer2.id} observered data:`, data);
})
observable.emit('change', {a: 1});
observable.emit('haha', [1, 2, 3]);
参考:https://blog.csdn.net/bdss58/article/details/51473107
|