0

Javascript - can't modify/change var object value inside function?

var shared = {
        lock: true,
        connection: '',
        messages: []
    };

Socket.onopen = function(e)
    {
        shared.connection = 'Zostałeś połączony pomyślnie!';
        shared.lock = false;
    };

Something like this, and it doesn't work.

But code is proper, because something like this

shared.connection = 'Zostałeś połączony pomyślnie!';
Socket.onopen = function(e)
        {
            shared.lock = false;
        };

does work.

so It's like I can't modify shared.connection inside this function...

But what's strange

Socket.onerror = function(e) { shared.messages.push(generateMessage('System', 'Wystąpił błąd! Połączenie zostało przerwane.', 'others')); shared.lock = true; };

This one works, pushes properly message to messages array in shared.

What's up? What is going on?

How to get it work?

Full code:

<script>

    var shared = {
        lock: true,
        connection: '',
        messages: []
    };

    function generateMessage(nick = '', content = '', color = '')
    {
        return {
            time: timeNow(),
            nick: nick,
            content: content,
            color: color
        };
    }

    function timeNow()
    {
        var date = new Date();
        return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    }

    export default {
        data() {
            return {
                lock: shared.lock,
                connection: shared.connection,
                login: true,
                message: {
                    time: '',
                    nick: '',
                    content: '',
                    color: 'others'
                },
                messages: shared.messages
            }
        },
        methods:
        {
            submit: function()
            {
                var date = new Date();
                this.message.time = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
                Socket.send(JSON.stringify(this.message));
                this.message.color = '';
                this.messages.push(JSON.parse(JSON.stringify(this.message)));
                this.login = false;
                this.message.color = 'others';
                this.message.content = '';
            }
        }
    }

    var Socket = new WebSocket('ws://localhost:9000/chat');

    Socket.onopen = function(e)
    {
        shared.connection = 'Zostałeś połączony pomyślnie!';
        console.log(shared.connection);
        shared.lock = false;
    };

    Socket.onmessage = function(e)
    {
        shared.messages.push(JSON.parse(e.data));
    };

    Socket.onerror = function(e)
    {
        shared.messages.push(generateMessage('System', 'Wystąpił błąd! Połączenie zostało przerwane.', 'others'));
        shared.lock = true;
    };

    Socket.onclose = function(e)
    {
        shared.messages.push(generateMessage('System', 'Połączenie zostało zamknięte.', 'others'));
        shared.lock = true;
    };


</script>

This question is different because we are facing here VueJS which comes with reactivity and var value can be changed in the future.

Socket.onopen = function(e)
    {
        shared.connection = 'Zostałeś połączony pomyślnie!';
        shared.messages.push(generateMessage('System', 'Wystąpił błąd! Połączenie zostało przerwane.', 'others'));

shared.messages.push(generateMessage('System', 'Wystąpił błąd! Połączenie zostało przerwane.', 'others')); this one works good, messages in Vue updates and I can see it,

but shared.connection = 'Zostałeś połączony pomyślnie!'; doesn't work, nothing updates in vue... What is going on ? :/

It updates the value, but Vue doesn't get it.

I think it is something with vue..

enter image description here

enter image description here

Krystian Polska
  • 1,286
  • 3
  • 15
  • 27
  • 2
    You're not showing any code that would give you an indication that `shared` is not being modified. Probably an async issue, but still can't tell without a full demo. – llama Oct 12 '17 at 20:37
  • That is just it, nothing else modifies shared.connection and as you can see putting this before this function works @llama – Krystian Polska Oct 12 '17 at 20:38
  • 1
    Sure, but what makes you think it's not modified? Only way to tell would be to try to examine your mutations somewhere, but you're not showing that. – llama Oct 12 '17 at 20:39
  • You're code seems to work fine, not sure what the issue is. – djfdev Oct 12 '17 at 20:40
  • @llama I am sure because it is the only line of code that modifies that and because even putting it before function works, it's just something bad about being this inside this function – Krystian Polska Oct 12 '17 at 20:40
  • 1
    I'll try one more time. You're assigning some values to the object properties. We get that. But for some reason you've gotten the idea that the values didn't actually get assigned. What is giving you that idea? Nothing in your example would indicate a post-mutation examination of the object that would lead you to the conclusion you reached. – llama Oct 12 '17 at 20:42
  • https://jsbin.com/jubogic/edit?js,console – djfdev Oct 12 '17 at 20:46
  • I think it doesn't modify the value, I changed to `xxx` for initial, `connection: 'xxx',` and after onopen nothing changes. but onopen works, tried even `console.log('aaa");` inside onopen – Krystian Polska Oct 12 '17 at 20:58
  • Surely the `console.log(shared.connection);` right after `shared.connection = 'Zostałeś połączony pomyślnie!';` does log the expected value, doesn't it? I bet the one that's "not modified" is one of the results of calling `data()`, right? – Bergi Oct 12 '17 at 21:28
  • Some other things to improve: you're using ES6 module syntax inside a ` – Bergi Oct 12 '17 at 21:31
  • @Bergi using Laravel-Mix (so webpack) – Krystian Polska Oct 13 '17 at 07:20
  • @Bergi yes right about this `data()` – Krystian Polska Oct 13 '17 at 08:21
  • @Bergi please come here mate :D – Krystian Polska Oct 14 '17 at 13:53
  • @Bergi please help me : / – Krystian Polska Oct 19 '17 at 17:35
  • Have you understood the problem that was described in the duplicate question? – Bergi Oct 19 '17 at 17:40
  • @Bergi I think I have understood, but I use Vue here, reactivity is here. And it worked well before I seperated this in component file, before I have one big file inline in php front-end. I have read whole duplicate you assigned and I tried some things, but didn't work + I don't think it is about this especially due to Vue – Krystian Polska Oct 19 '17 at 18:15
  • Can you post the working code and the full separated-component non-working code, please? – Bergi Oct 19 '17 at 22:42

0 Answers0