2021-09-13 16:54:32 +00:00
|
|
|
class Speaker {
|
|
|
|
#callbacks = new Set()
|
|
|
|
#immediate
|
|
|
|
#scheduled = []
|
2021-11-25 09:20:31 +00:00
|
|
|
#retain
|
2021-09-13 16:54:32 +00:00
|
|
|
|
2021-11-25 09:20:31 +00:00
|
|
|
constructor(immediate, ...initial) {
|
2021-09-13 16:54:32 +00:00
|
|
|
this.#immediate = immediate
|
2021-11-25 09:20:31 +00:00
|
|
|
this.#retain = initial
|
2021-09-13 16:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
listen(callback) {
|
|
|
|
this.#callbacks.add(callback)
|
2021-11-25 09:20:31 +00:00
|
|
|
return this.#retain
|
2021-09-13 16:54:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
speak(...args) {
|
|
|
|
if (this.#immediate) {
|
|
|
|
for (let callback of this.#callbacks) {
|
|
|
|
callback(...args)
|
|
|
|
}
|
2021-11-25 09:20:31 +00:00
|
|
|
this.#retain = args
|
2021-09-13 16:54:32 +00:00
|
|
|
} else {
|
|
|
|
if (!this.#scheduled.length) {
|
|
|
|
queueMicrotask(() => {
|
2021-10-19 16:28:57 +00:00
|
|
|
for (let args of this.#scheduled) {
|
|
|
|
for (let callback of this.#callbacks) {
|
|
|
|
callback(...args)
|
|
|
|
}
|
2021-11-25 09:20:31 +00:00
|
|
|
this.#retain = args
|
2021-09-13 16:54:32 +00:00
|
|
|
}
|
|
|
|
this.#scheduled = []
|
|
|
|
})
|
|
|
|
}
|
|
|
|
this.#scheduled.push(args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
silence(callback) {
|
|
|
|
this.#callbacks.delete(callbacks)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Speaker
|