jmasterx
jmasterx

Reputation: 54113

What might be wrong with my class?

I am working on a class to have callbacks to a web socket:

function QB() {
    var ws = null;

    this.connect = function () {
        // Let us open a web socket
        ws = new WebSocket("ws://localhost:9000/koule");

        ws.onopen = function () {
            if (this.onConnectionEstablished) {
                this.onConnectionEstablished();
            }
        };
        ws.onmessage = function (evt) {
            var msg = evt.data;
            //process callbacks
            parseMessage(msg);

        };
        ws.onclose = function () {
            if (this.onConnectionClosed) {
                this.onConnectionClosed();
            }
        };
        ws.onerror = function () {
            if (this.onConnectionError) {
                this.onConnectionError();
            }
        };
    };




    this.onConnectionEstablished = null;
    this.onConnectionClosed = null;
    this.onConnectionError = null;
}

Then I use it in this sample:

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript" src="qb.js"></script>
    </head>
    <body>

        <h1>My First JavaScript</h1>

        <p>Click Date to display current day, date, and time.</p>

        <button type="button" onclick="myFunction()">Date</button>

        <p id="demo"></p>

        <script>
            qb = new QB();


            qb.onConnectionEstablished = function()
            {
                alert('connected');
            };

        qb.onConnectionError = function()
        {
            alert('error');

        };

        qb.onConnectionClosed = function()
        {
            alert('closed');
        };


            function myFunction() {
                qb.connect();
            }
        </script>

    </body>
</html> 

I do not get any of the alerts and I should be getting at least one of them. I checked in Chrome and my qb is correctly created and its ws variable has the callbacks hooked to it and the qb has the callbacks I set.

I cannot figure out why this is not working.

Thanks

Upvotes: 1

Views: 48

Answers (1)

Imperative
Imperative

Reputation: 3183

The this scope inside the anonymous functions is not the this of your QB instance:

ws.onopen = function () {
    if (this.onConnectionEstablished) {                  
         this.onConnectionEstablished()
    }
};

It should work like so:

var self = this;
ws.onopen = function () {
    if (self.onConnectionEstablished) {                  
         self.onConnectionEstablished()
    }
};

Upvotes: 2

Related Questions