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