CFWEBSOCKET - unable to call websocket object in Javascript

731 Views Asked by At

I'm using the cfwebsocket tag in Coldfusion to create a web socket connection. I looked at an example from here http://www.sagarganatra.com/2012/03/html5-websockets-in-coldfusion-10.html and near the end it shows you all the javascript calls you can make on the web socket object. However, when I try to make any call on it I get an error that it is undefined. For example I have:

<cfwebsocket name="ws" onMessage="messageHandler" onOpen="openHandler" onClose="closeHandler" onError="errorHandler" subscribeTo="chat" />

and in my javascript i call

alert(ws.isConnectionOpen());

and I get the error in firebug: TypeError: ws is undefined.

Anyone know why I can't call it? My chat works fine and I can connect and chat properly. I just wanted to close the connection when the chat ended so I was looking into how it's done calling the websocket but I don't know why it's not working.

Note that I am using jQuery and the javascript is wrapped in the document ready.

1

There are 1 best solutions below

0
On

First, you can't interact with the ws object till it establishes a connection to the server.

There are a couple of ways to handle this scenario. You can use the "onOpen" attribute and have it call a function once the web socket connect has been established.

However, you are probably better off just using the "onMessage" attribute and create a generic listener function that processes all web socket messages from the server.

function messageHandler(msg) {

    if (msg.type == 'response' && msg.reqType == 'welcome'){

        alert('user connected');
    }       
}