Eunice Chia Eunice Chia - 4 months ago 21
Node.js Question

Closure confusion, share global variable between function

var data = null;

socket.on('screen1', function (data) {

data = data;
console.log(data) // has something
});

$approve.click(function(){
console.log(data) //null
socket.emit('screen2', data);

});


For some reason I can't put click event into socket.on because it's listening to the server. But I want its callback which is the
data
.I tried to do data = data and expect my click callback is able to get the data but it's still null.

Answer

Your local variable takes precedence over the global variable:

socket.on('screen1', function (data) { // <-- local variable "data"
    data = data;  // <-- both these "data" are the same variable!!
});

To access the global variable "data" rename the local variable to something else:

socket.on('screen1', function (d) {
    // Here I have no idea what your intention is. If I am
    // confused consider how the compiler is supposed to read
    // your mind.

    // You either wanted to do:
    d = data;

    // or data = d;

    // I cannot guess and neither can the compiler.
});