Implemented socket on and off correctly
This commit is contained in:
parent
b0efec811e
commit
a685cbbf66
2600
public/js/bundle.js
2600
public/js/bundle.js
File diff suppressed because one or more lines are too long
@ -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(key) {
|
||||||
|
if (Object.keys(this.listeners).indexOf(key) != -1){
|
||||||
|
console.log('off:', key)
|
||||||
|
this.removeEventListener('message', this.listeners[key])
|
||||||
|
delete this.listeners[key]
|
||||||
}
|
}
|
||||||
off() {
|
|
||||||
console.log('off!')
|
|
||||||
// this.removeEventListener('message')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user