パブリッシュおよびサブスクライブ
class EventEmitter {
constructor() {
this.subs = Object.create(null);
}
$on(eventType, handler) {
if (this.subs[eventType]) {
this.subs[eventType].push(handler);
} else {
this.subs[eventType] = [handler];
}
}
$emit(eventType) {
if (this.subs[eventType]) {
this.subs[eventType].forEach(handler => handler())
}
}
}
const eventHub = new EventEmitter();
eventHub.$on('test', () => {
console.log('收到啦~');
});
eventHub.$on('test', () => {
console.log('收到啦~');
});
eventHub.$emit('test');
観察者
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
if (sub && sub.update) {
this.subs.push(sub);
}
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
class Watcher {
update() {
console.log('update');
}
}
const dep = new Dep();
const watcher = new Watcher();
dep.addSub(watcher);
dep.notify();