Search the Community
Showing results for tags 'lifetime'.
-
Hi, I'm trying to create a small javascript app which loads a JSON url and displays some html and divs based on the JSON data. It's got to be as small as possible so without using a frameworks like Phaser and jQuery. The javascript scope of variables is a bit tricky, and I'm having some trouble getting it to work properly. My question is, how can create the MyGame class with an imageShapes image and then reference that imageShapes in the onreadystatechange method of XMLHttpRequest? Here is my code:// namespacevar MyGame = MyGame || { gamedata: [], test123: 'This is a test value 123'};// game objectMyGame.start = function (jsonfilename) { // initialise image this.imageShapes = new Image(); // add gamedata and populate by loading json this.gamedata = []; this.test123 = 'This is a test value 123'; this.loadJSON( jsonfilename, this.onJSONsuccess, // <- function to call on successfully loaded JSON this.onJSONerror );}MyGame.start.prototype = { // load a JSON file loadJSON: function(path, success, error) { console.log('TESTING loadJSON : test123='+this.imageBackground); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if ((xhr.status === 200) || (xhr.status === 0)) { // status 0 = local file testing if (success) success(JSON.parse(xhr.responseText)); // <- how to reference back to "MyGame" ? } else { if (error) error(xhr); } } }; xhr.open("GET", path, true); xhr.send(); }, // handle load json events onJSONerror: function(xhr) { console.log('MyGame.js - onJSONerror error loading json file'); console.error(xhr); }, onJSONsuccess: function(data) { // load data from JSON this.gamedata = data; console.log('TESTING -- data.imgshapes='+data.imgshapes+' test123='+MyGame.test123+' imageShapes='+this.imageShapes); // this.imageShapes is also undefined MyGame.imageShapes.src = 'img/mybackground.png'; // <- problem is here, imageShapes is undefined..? }};var test = new MyGame.start('js/mydatafile.json');When I try the code above, it fails in onJSONsuccess. The imageShapes cannot reference and it is undefined, even though I defined it earlier in the MyGame class. This is the error: Uncaught TypeError: Cannot set property 'src' of undefined test123.js:58
- 5 replies
-
- javascript
- scope
-
(and 3 more)
Tagged with: