// 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
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.