hoaproject / Websocket

The Hoa\Websocket library.
https://hoa-project.net/
423 stars 75 forks source link

Vue and websocket #94

Open YnievesDotNet opened 7 years ago

YnievesDotNet commented 7 years ago

I try to use the demo code, on one app and I use vue in this app, but the code is broken and I recive this error

Uncaught TypeError: Cannot read property 'addEventListener' of null

Thanks.

Yoinier.

Hywan commented 7 years ago

Maybe a little bit of code would help a lot :-).

YnievesDotNet commented 7 years ago

That is my code

...
        <input type="text" id="input" placeholder="Message…" />
        <hr />
        <pre id="output"></pre>
...
<script>
    var host   = 'ws://127.0.0.1:8000';
    var socket = null;
    var input  = document.getElementById('input');
    var output = document.getElementById('output');
    var print  = function (message) {
        var samp       = document.createElement('samp');
        samp.innerHTML = message + '\n';
        output.appendChild(samp);

        return;
    };

    input.addEventListener('keyup', function (evt) {
        if (13 === evt.keyCode) {
            var msg = input.value;

            if (!msg) {
                return;
            }

            try {
                socket.send(msg);
                input.value = '';
                input.focus();
            } catch (e) {
                console.log(e);
            }

            return;
        }
    });

    try {
        socket = new WebSocket(host);
        socket.onopen = function () {
            print('connection is opened');
            input.focus();

            return;
        };
        socket.onmessage = function (msg) {
            print(msg.data);

            return;
        };
        socket.onclose = function () {
            print('connection is closed');

            return;
        };
    } catch (e) {
        console.log(e);
    }
</script>
<script src="/js/app.js"></script>

Thanks, Yoinier.

Pierozi commented 7 years ago

Hello @YnievesDotNet This error means the DomElement input is not yet ready when the Javascript is executed. You should embed the javascript code on function and execute it after the onload event.