-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.ts
53 lines (46 loc) · 1.51 KB
/
core.ts
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
import { Channel, Subscription, Callback, Cache, create } from "./channel.ts"
import { Disposer } from "./disposer.ts"
import { Optional } from "./utils.ts"
export default class WhatBus {
closed = false
cache = new Cache
disposer = new Disposer
prefix: string
constructor(prefix: string = '') {
this.prefix = prefix
}
channel(name: string) {
if (this.closed) throw new Error(`WhatBus(${this.prefix}) is closed`)
const channel = create(this.prefix + name)
this.disposer.add(channel)
return channel
}
publish(name: string, data: any) {
// check cache for corresponding channel
let channel: Optional<Channel> = this.cache.get(name)
if (!channel) {
// create new channel and add to cache
channel = this.channel(name)
this.cache.set(name, channel)
}
channel.postMessage(data)
// channel will be closed when it falls out of the cache
}
subscribe(name: string, callback: Callback): Subscription {
const channel = this.channel(name)
channel.onmessage = callback
return channel as Subscription
}
subscribeOnce(name: string, callback: Callback): Subscription {
const subscription = this.subscribe(name, (e: MessageEvent) => {
subscription.dispose()
callback(e)
})
return subscription
}
close() {
this.closed = true
this.cache.dispose()
this.disposer.dispose()
}
}