Created
March 5, 2020 23:30
-
-
Save cnnrznn/8c266e9e4b4e85961103e805417f6373 to your computer and use it in GitHub Desktop.
Scope of "this"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Doesn't work */ | |
class Transport extends EventEmitter.EventEmitter { | |
constructor() { | |
super(); | |
this.connected = false; | |
this.ws = new WebSocket("ws://localhost:8081"); | |
this.ws.onmessage = fromServer; | |
this.ws.onopen = function(event) { | |
this.connected = true; | |
} | |
this.ws.onclose = function(event) { | |
this.connected = false; | |
console.log("Connection closed"); | |
// TODO: reconnect? | |
} | |
this.ws.onerror = function(event) { | |
console.log("Error in websocket"); | |
} | |
} | |
fromServer(data) { | |
var edit = JSON.parse(data.data); | |
edit.delta = new Delta(edit.delta); | |
this.emit('edit', edit); // "this" refers to websocket 'ws' | |
} | |
push(edit) { | |
this.ws.send(JSON.stringify(edit)); | |
} | |
} | |
/** This works **/ | |
import EventEmitter from 'events'; | |
import Delta from 'quill-delta'; | |
class Transport extends EventEmitter.EventEmitter { | |
constructor() { | |
super(); | |
this.ws = new WebSocket("ws://localhost:8081"); | |
////////////////////////////////////////////////////////////////////////// | |
// workaround | |
this.ws.onmessage = (data) => { | |
var edit = JSON.parse(data.data); | |
edit.delta = new Delta(edit.delta); | |
this.emit('edit', edit); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
this.ws.onopen = function(event) { | |
this.connected = true; | |
} | |
this.ws.onclose = function(event) { | |
this.connected = false; | |
console.log("Connection closed"); | |
// TODO: reconnect? | |
} | |
this.ws.onerror = function(event) { | |
console.log("Error in websocket"); | |
} | |
} | |
push(edit) { | |
this.ws.send(JSON.stringify(edit)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment