|
@@ -3,51 +3,59 @@
|
|
|
* 一个简单的发布者、订阅者模式,提供了发布、订阅、删除的方法
|
|
|
* from chinyan
|
|
|
*/
|
|
|
-class PubsubService {
|
|
|
- private topics: Record<string, ((params?: any) => void)[]> = {}
|
|
|
+const PubsubService = (function () {
|
|
|
+ const topics: Record<string, ((params?: any) => void)[]> = {}
|
|
|
|
|
|
// 发布事件
|
|
|
- publish(topic: string, data: any) {
|
|
|
- if (!this.topics[topic]) return
|
|
|
- this.topics[topic].forEach((fn) => fn(data))
|
|
|
+ function publish(topic: string, data: any) {
|
|
|
+ if (!topics[topic]) return
|
|
|
+ topics[topic].forEach((fn) => fn(data))
|
|
|
}
|
|
|
|
|
|
// 订阅事件
|
|
|
- subscribe(topic: string, callback: (params?: any) => void) {
|
|
|
- if (!this.topics[topic]) {
|
|
|
- this.topics[topic] = []
|
|
|
+ function subscribe(topic: string, callback: (params?: any) => void) {
|
|
|
+ if (!topics[topic]) {
|
|
|
+ topics[topic] = []
|
|
|
}
|
|
|
|
|
|
- if (!this.topics[topic].includes(callback)) {
|
|
|
- this.topics[topic].push(callback)
|
|
|
+ if (topics[topic].includes(callback)) {
|
|
|
+ return // 已经订阅过,不重复添加
|
|
|
}
|
|
|
|
|
|
+ topics[topic].push(callback)
|
|
|
// 返回取消订阅的方法
|
|
|
- return () => {
|
|
|
- const index = this.topics[topic].indexOf(callback)
|
|
|
+ return function unsubscribe() {
|
|
|
+ const index = topics[topic].indexOf(callback)
|
|
|
if (index !== -1) {
|
|
|
- this.topics[topic].splice(index, 1)
|
|
|
+ topics[topic].splice(index, 1)
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 清空所有订阅者
|
|
|
- clearAllSub() {
|
|
|
- this.topics = {}
|
|
|
+ function clearAllSub() {
|
|
|
+ for (const key in topics) {
|
|
|
+ topics[key] = []
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
// 清空某个主题的订阅者
|
|
|
- clearSubsByTopic(topic: string) {
|
|
|
- if (this.topics[topic]) {
|
|
|
- this.topics[topic] = []
|
|
|
- }
|
|
|
+ function clearSubsByTopic(topic: string) {
|
|
|
+ topics[topic] = []
|
|
|
}
|
|
|
|
|
|
// 判断是否有某个主题的订阅者
|
|
|
- hasSubsByTopic(topic: string) {
|
|
|
- return this.topics[topic] && this.topics[topic].length > 0
|
|
|
+ function hasSubsByTopic(topic: string) {
|
|
|
+ return topics[topic] && topics[topic].length > 0
|
|
|
+ }
|
|
|
+
|
|
|
+ return {
|
|
|
+ publish,
|
|
|
+ subscribe,
|
|
|
+ clearSubsByTopic,
|
|
|
+ clearAllSub,
|
|
|
+ hasSubsByTopic
|
|
|
}
|
|
|
-}
|
|
|
+})()
|
|
|
|
|
|
-// 实例化并导出单例
|
|
|
-export default new PubsubService()
|
|
|
+export default PubsubService
|