简单实现观察者
class SubPub {
constructor() {
this.subs = {};
this.hasObj = this.subs.hasOwnProperty;
}
subscribe(eventName, callback) {
if (!this.hasObj.call(this.subs, eventName)) {
this.subs[eventName] = [];
}
this.subs[eventName].push(callback);
}
removeSubscribe(eventName) {
if (!this.hasObj.call(this.subs, eventName)) {
console.error("not find ", eventName);
return;
}
delete this.subs[eventName];
}
publish(eventName, data) {
if (!this.hasObj.call(this.subs, eventName)) {
console.error("not find ", eventName);
return;
}
this.subs[eventName].forEach((callback) => {
callback(data);
});
}
}
const sub = new SubPub();
sub.subscribe("change", (data) => {
console.log("改变为:", data);
})
sub.publish("change", "wang")
sub.publish("aaa", "wang")