------NOTE: SEE SOLUTION AT THE END OF THIS POST-------
I'm trying to make a simple websocket library, that allows to have one callback on connect, one callback on message received and automatic reconnection if it does no receive a message after 5 seconds.
<html>
<script>
function ws(url, cb, concb){
this.timeout = setTimeout(this.timeoutCB, 5000);
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = () => {
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = function() {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(this.timeoutCB, 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = () => {
alert("PRESS OK TO RECONNECT");
this.timeout = setTimeout(this.timeoutCB, 5000);
this.startConnection();
}
w = new ws("127.0.0.1:9000", null, null);
</script>
</html>
I created a startConnection
method to be able to call it in both the constructor and the timeoutCB
method. The problem is, when I call this.startConnection
from the constructor, this is not the ws object but window
. I don't know how I can create a method startConnection
I can call from both the constructor and another method such as timeoutCB
------------------- SOLUTION ----------------------------------------------------
Please review Nick Parsons' comments. Here's the code that works for me after applying his suggestions:
function ws(url, cb, concb){
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = function() {
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
console.log(this)
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = () => {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = function() {
alert("PRESS OK TO RECONNECT");
this.startConnection();
}