订阅/发布者模式
订阅发布模式:一对多的关系,让多个观察者同时监听某一个主题对象,这个主题对象的状态发生改变时就会通知所有观察者对象,中间通过一个调度中心来发布通知
function Dep(){
this.subs = [];
}
Dep.prototype.addSub = function(sub){
this.subs.push(sub);
}
Dep.prototype.notify = function(){
this.subs.forEach(sub => sub.update())
}
function load1 (){}
load1.prototype.update = function(){
console.log('load1')
}
function load2 (){}
load2.prototype.update = function(){
console.log('load2')
}
var dep = new Dep();
var watcher1 = new load1()
var watcher2 = new load2()
dep.addSub(watcher1)
dep.addSub(watcher2)
dep.notify();
// https://www.cnblogs.com/suyuanli/p/9655699.html
class Event{
constructor(){
handlers = {};
}
on(type, handler){
if (!(type in this.handlers)) {
this.handlers[type] = [];
}
this.handlers[type].push(handler);
}
emit(type, ...params){
if (!(type in this.handlers)) {
return new Error('未注册!')
}
this.handlers[type].forEach(handler => {
handler(...params);
});
}
// 移除
remove(type, handler){
if (!(type in this.handlers)) {
return new Error('无效事件');
}
if (!handler) { // 没有指明handler,移除type
delete this.handlers[type];
} else {
const idx = this.handlers[type].findIndex(ele => ele === handler);
if (idx === undefined) {
return new Error('no')
}
this.handlers[type].splice(idx, 1);
if (this.handlers[type].length === 0) {
delete this.handlers[type];
}
}
}
}
function load(params){
console.log('load', params)
}
function foo(params){
console.log('foo...', params)
}
var event = new Event();
event.on('load', load);
event.on('load', foo);
// 触发
event.emit('load', 'load触发')
// 移除foo
event.remove('load', foo);
event.emit('load')