Skip to content
This repository has been archived by the owner on Sep 20, 2021. It is now read-only.

Vue and websocket #94

Open
YnievesDotNet opened this issue Jun 12, 2017 · 3 comments
Open

Vue and websocket #94

YnievesDotNet opened this issue Jun 12, 2017 · 3 comments

Comments

@YnievesDotNet
Copy link

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
Copy link
Member

Hywan commented Jun 12, 2017

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

@YnievesDotNet
Copy link
Author

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
Copy link
Member

Pierozi commented Jun 12, 2017

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Development

No branches or pull requests

3 participants