1

I have an issue with the scope in the filereader() code i have. I have two console.logs() outputting the data from a JSON file uploaded. One outputs as expected, within the function parsing the JSON. The other outputs the 'template' data/object. It looks to me like its a scope issue. Where should i define the updated character object to have the parsed JSON data update the character object?

The function should import a JSON file, parse it then string it into a textarea and also take the parse and put the output into a character object referable by the whole page.

The character object being imported, is an exported version of the character object from another user session.

$('#import').click(function(){

  var iData = document.getElementById('selectFiles').files;
  console.log(iData);
  if (iData.length <= 0) {
    return false;
  }

  var file = new FileReader();

  file.onload = function(x) { 
    console.log(x);
    var output = JSON.parse(x.target.result);
    var stringed = JSON.stringify(output,null,2);
    document.getElementById('result').value = stringed;
    character = output;
    console.log(character); //this outputs the data as expected
  }

  console.log(character);//this outputs blank 'template' data
  file.readAsText(iData.item(0));
});

I posted something similar to this the other day, but the post was a bit.... bad, if i'm honest. Hopefully i've poked about enough to make this one a little better.

Thanks

James Kraus
  • 3,349
  • 20
  • 27
Kalacia
  • 76
  • 5
  • 1
    `console.log(character);//this outputs blank 'template' data` is fired already before the `onload` function is finished. By that time, `character` variable is still not updated by your callback. – xGeo May 26 '17 at 13:41
  • Thank you, i can work with this. Ill also check out the dupe. – Kalacia May 26 '17 at 13:59

1 Answers1

2

The console.log that works is inside of your onload function, this means it won't get called until the function successfully loads your JSON. The second console.log doesn't work because it is called before your JSON has a chance to load.

Benjamin Commet
  • 350
  • 3
  • 8