const _pond = Symbol();
class Subscribe {
constructor() {
this[_pond] = new Map();
}
add(key, fn) {
if (typeof key != "string" && typeof fn != "function") {
throw 'key是一个字符串,fn是一个函数';
}
this[_pond].set(key, fn);
}
remove(key) {
this[_pond].delete(key)
}
fire(...args) {
for (const value of this[_pond].values()) {
value.call(this,...args);
}
}
}
- Symbol定义让pond事件池私有
- 添加方法使用map,又实现了去重
- remove删除事件池的某个方法
- fire订阅者,依次执行
let sub = new Subscribe();
sub.add('a',function(a){
console.log(1);
})
sub.add('b',function(b){
console.log(2);
})
sub.add('c',function(c){
console.log(3);
});
sub.fire();