0

I was having an issue with Node.js, socket etc. This may be an overall javascript question but i am having problems.

I don't know how to pull data out of a function and set it to a global var.

It's stuck in the below function and i cant effect the DOM (or html document, to keep the language simple). I am new to Node and socket.io and been working with Javascript for about a month now and slowly getting my head around but this seems like a simple question i cant get an answer to. Pull var from function and make global, should be simple?

var markets; // if I remove this I get Uncaught ReferenceError: markets is not defined and everything else breaks
console.log(markets); //this is undefined in the console, this is where the problem arises, how do i get the data from out of the below function?
var socket = io.connect('http://localhost'); 
socket.on('ready', function (data) {
    console.log(data); // correctly outputs all data from server
    for (var i = 0; i < data.length; i++) {;
        item = data[i]; // just pulling one array from the database... i think?
        createBox(item); //not really sure what this does
    };
    console.log(item); // this outputs one Object
    markets = item; //this is defining item as being markets
});

function createBox(item) {
    var box = document.createElement('div');
    var itemName = document.createTextNode(item.name);
    document.body.appendChild(itemName);
    console.log(item.name);
};
user229044
  • 232,980
  • 40
  • 330
  • 338
React Dev
  • 420
  • 2
  • 6
  • 16
  • Please improve this quiestion. The way the code is set now, you want to make 'markets' hold the *last* item in your 'data' array. Maybe you want to make markets an array? like var markets = []; and then in your socket.on('ready') callback function, push items into the markets array? – Zlatko Feb 20 '14 at 23:53
  • Additionally, you may want to namespace your stuff, not make all of that global. To wrap my head around js, it really helped me to watch the Douglas Crockford videos, "Javascript, the good parts" - the six of them made me gradually get more and more stuff and work from there. – Zlatko Feb 20 '14 at 23:55
  • `markets = item; //this is defining item as being markets` No, it's setting `markets` to the value of `item`. It's unclear what you're asking. What makes you think that you *aren't* setting a global variable? Based on the code posted, you're definitely setting the global variable `markets` to the value of the last `item` generated by your loop. – user229044 Feb 20 '14 at 23:56
  • Is the code above in your web page / running in the browser or is that the code you're trying to run inside your node.js process? – Chris Tavares Feb 20 '14 at 23:59
  • **No**, do not even try to "*make global*". See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call); the problem is the same with your socket. – Bergi Feb 21 '14 at 01:38

0 Answers0