Just an Example here, Using websocket in browser. Same happened when using Nodejs with ws Library for Websocket.
If you write everything out side a class, all the handlers will be called: EG:
try {
var host = "ws://localhost:8080";
var socket = new WebSocket(host);
socket.onopen = function(){
// Do something
}
socket.onmessage = function(msg){ // all stuff here will be called upon receiving message
// Do something
}
socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
How ever, if you want to instantiate in a class, non of the handlers will be called
var ws = new webSocketModule();
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
this.socket = new WebSocket(host);
this.socket.onopen = function(){
// Do something
}
this.socket.onmessage = function(msg){ // None of these are called upon receiving message, however the server side will have connection message that means the websocket object is functioning just fine.
// Do something
}
this.socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}
So is it that I have to do it the messy way of putting everything globally?
To Add to the question
var ws = new webSocketModule();
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
this.socket = new WebSocket(host);
this.socket.onopen = function(){
// Do something
}
this.socket.onmessage = function(msg){
// Do something
}
this.socket.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}
ws.socket.onmessage = function(msg){
// This will be called, kinda confusing
}
================================================================= Added:
var ws = new webSocketModule(); //Explain: This is the instance in the main file
// Down below is in eg: webSocketModule.js
var webSocketModule = function(){
try {
var host = "ws://localhost:8080";
var skt = this.socket = new WebSocket(host);
skt.onopen = function(){
// Do something
}
skt.onmessage = function(msg){
// Using a local variable for socket will not make this respond
// Another side will successfully show connected and send the message
// (At least it successfully printed the console log after the socket.send)
// You have to register it like the above block "ws.socket.onmessage = ..." in the main file to make it respond
// But this and the object should be the same point of reference right?
// Seems Javascript handles it differently than JAVA or C++, is there any book that recommended that talks about how browser or NodeJS handles it? thanks.
// Do something
}
skt.onclose = function(){
// Do something
}
} catch(exception){
// Do something
}
}