Handling websocket callbacks

When a websocket callback handler function is called, this refers to the Websocket instance.

There is no way to get access to the scene, so my first attempt was to simply say

socket.scene = this

inside the scene create event.

Does this sound like a reasonable solution? Can you give me any guidance in this matter?

OK, after some searching and reading, I have managed to find the solution to my problem (which was that this in the websocket callback always pointed to the WebSocket instance.

(This is really a lack-of-Javascript-knowledge problem, not a Phaser issue, but I am still fairly new to Javascript).

        let socket = new WebSocket("ws://" + location.host + "/ws")
        function sock_msg_handler(message) {
          ...
        }
        // sock_msg_handler.bind(_this) <-- Does not work!
        socket.onmessage = function(message) {
            sock_msg_handler.call(this, message)
        }.bind(this)

For some reason, binding the current context of the scene to the callback function does not ensure that the scene is set as the context object in the callback.

However, using an anonymous function with bind(this) does.

Why, I don’t know. But from here on, the context in this is correctly set to the scene, so I can carry on.

yes~ you are right! that = this

socket.onmessage = function(message) {
that.add.text(1,1,‘text’)
}