In my case I have done with this approach,
- I have created one JS file for WebSocket event handling methods(onOpen,onClose and onMessage) which is loaded on home page loading.
- In this file I have created one reference variable to hold events of WebSockets using (.prototype)
- Same like second step created two seperate methods for creating connection which is going to be called from home page and one connect method to connect the server
- In onMessage you can call your business method where you can put your logic
code look like,
var _wObj = null;
function WSSocket(tObj) {
//basic properties
}
create connection
WSSocket.createConnection = function ( tObj ) {
if (!_wObj) {
_wObj = new WSSocket(tObj);
}
return _wObj;
}
connect to server
WSSocket.prototype.connect = function () {
//connection logic
}
register events
WSSocket.prototype.registerEvents = function () {
//registering logic
this.wObj.onmessage = function (event) {
//call your operation method
}
}