// JS 的内置发布订阅
// create custom events
const catFound = new CustomEvent("animalfound", {
detail: {
name: "cat",
},
});
const dogFound = new CustomEvent("animalfound", {
detail: {
name: "dog",
},
});
const element = document.createElement("div"); // create a <div> element
// add an appropriate event listener
element.addEventListener("animalfound", (e) => console.log(e.detail.name));
// dispatch the events
element.dispatchEvent(catFound);
element.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console
// 我的自定义发布订阅,我的桌面应用移动应用网页应用都是用它驱动的。
export class StateManage<T> {
private inValue: T
private publishChangeCalls: (() => void)[] = []
constructor(v: T) {
this.inValue = v
}
subscriptChange(subCall: () => void) {
this.publishChangeCalls.push(subCall)
}
unsubscriptChange(subCall: () => void) {
this.publishChangeCalls = this.publishChangeCalls.filter(sub => !Object.is(sub, subCall))
}
set value(v: T) {
this.inValue = v
this.publishChangeCalls.forEach(call => call())
}
get value(): T {
return this.inValue
}
}
|