0

I am trying to get data from json file to render tilemap. But I am getting this error all the time Uncaught ReferenceError: renderTileMap is not defined.

I tried to place body of renderTileMap function into $.getJSON function and it works. Map is rendered in 0.2 ms so no long waiting. JSON file is also correct. I have no idea why javascript cannot see this method.

getData() {
    $.getJSON(this.file, renderTileMap);
}

renderTileMap(json) {
    var actPosX = this.beginPosX;
    var actPosY = this.beginPosY;
    var activeTile = 0;

    var tiles = json.tiles;
    var tilesResources = json.tilesResources;
    var lines = tiles.length / this.lineSize;
    var i, y;
    for(i = 1; i < lines; i++) {
        for(y = 1; y < this.lineSize; y++) {
            ctx.fillStyle = tilesResources[tiles[activeTile]];
            ctx.fillRect(actPosX,actPosY, this.tileWidth, this.tileHeight);
            actPosX += this.tileWidth;
            activeTile++;
        }
        actPosY += this.tileHeight;
        actPosX = this.beginPosX;
    }
}
Filip Bartoš
  • 301
  • 3
  • 16

1 Answers1

2

Both file and renderTileMap aren't variables of the getData method, they are part of the context of getData (the object it is in). You can access the context via this so it has to be:

   $.getJSON(this.file, this.renderTileMap);

Now while the callback gets called now, it looses its context, so you have to bind it:

  $.getJSON(this.file, this.renderTileMap.bind(this));

Read on:

How to access the correct `this` inside a callback?

MDN - this

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151