-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageBroker.js
More file actions
87 lines (80 loc) · 2.74 KB
/
Copy pathMessageBroker.js
File metadata and controls
87 lines (80 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Author and copyright: Stefan Haack (https://shaack.com)
* Repository: https://github.com/shaack/cm-web-modules
* License: MIT, see file 'LICENSE'
*/
export class MessageBroker {
constructor() {
this.topics = []
}
subscribe(topic, callback) {
if(!topic) {
const message = "subscribe: topic needed"
console.error(message, callback)
throw new Error(message)
}
if(!callback) {
const message = "subscribe: callback needed"
console.error(message, topic)
throw new Error(message)
}
if (this.topics[topic] === undefined) {
this.topics[topic] = []
}
if (this.topics[topic].indexOf(callback) === -1) {
this.topics[topic].push(callback)
}
}
unsubscribe(topic = null, callback = null) {
if(callback !== null && topic !== null) {
this.topics[topic].splice(this.topics[topic].indexOf(callback), 1)
} else if (callback === null && topic !== null) {
this.topics[topic] = []
} else if (topic === null && callback !== null) {
for (const topicName in this.topics) {
// noinspection JSUnfilteredForInLoop
const topic = this.topics[topicName]
for (const topicSubscriber of topic) {
if(topicSubscriber === callback) {
// noinspection JSUnfilteredForInLoop
this.unsubscribe(topicName, callback)
}
}
}
} else {
this.topics = []
}
if(topic !== null) {
if(this.topics[topic] && this.topics[topic].length === 0) {
delete this.topics[topic]
}
}
}
publish(topic, object = {}, async = true) {
if(!topic) {
const message = "publish: topic needed"
console.error(message, object)
throw new Error(message)
}
const breadcrumbArray = topic.split("/")
let wildcardTopic = ""
for (const topicPart of breadcrumbArray) {
this.callback(wildcardTopic + "#", topic, object, async)
wildcardTopic += topicPart + "/"
}
this.callback(topic, topic, object, async)
}
callback(wildcardTopic, topic, object = {}, async = true) {
if (this.topics[wildcardTopic]) {
this.topics[wildcardTopic].forEach(function (callback) {
if(async) {
setTimeout(function () {
callback(object, topic)
})
} else {
return callback(object, topic)
}
})
}
}
}