Implemented socket on and off correctly

This commit is contained in:
RemixDev 2021-03-07 12:31:55 +01:00
parent b0efec811e
commit a685cbbf66
No known key found for this signature in database
GPG Key ID: B33962B465BDB51C
2 changed files with 1293 additions and 1325 deletions

File diff suppressed because one or more lines are too long

View File

@ -1,8 +1,7 @@
let wasEventListenerAdded = false
class CustomSocket extends WebSocket { class CustomSocket extends WebSocket {
constructor(args) { constructor(args) {
super(args) super(args)
this.listeners = {}
} }
emit(key, data) { emit(key, data) {
if (this.readyState !== WebSocket.OPEN) return false if (this.readyState !== WebSocket.OPEN) return false
@ -10,8 +9,9 @@ class CustomSocket extends WebSocket {
this.send(JSON.stringify({ key, data })) this.send(JSON.stringify({ key, data }))
} }
on(key, cb) { on(key, cb) {
if (!wasEventListenerAdded) { if (Object.keys(this.listeners).indexOf(key) == -1){
wasEventListenerAdded = true console.log('on:', key)
this.listeners[key] = cb
this.addEventListener('message', event => { this.addEventListener('message', event => {
const messageData = JSON.parse(event.data) const messageData = JSON.parse(event.data)
@ -21,10 +21,14 @@ class CustomSocket extends WebSocket {
} }
}) })
} }
} }
off() { off(key) {
console.log('off!') if (Object.keys(this.listeners).indexOf(key) != -1){
// this.removeEventListener('message') console.log('off:', key)
this.removeEventListener('message', this.listeners[key])
delete this.listeners[key]
}
} }
} }