简体   繁体   English

$ .getJSON回调函数未定义

[英]$.getJSON callback function is not defined

I am trying to get data from json file to render tilemap. 我正在尝试从json文件中获取数据以渲染tilemap。 But I am getting this error all the time Uncaught ReferenceError: renderTileMap is not defined . 但是我一直都遇到此错误Uncaught ReferenceError: renderTileMap is not defined

I tried to place body of renderTileMap function into $.getJSON function and it works. 我试图将renderTileMap函数的主体放入$ .getJSON函数中,并且可以正常工作。 Map is rendered in 0.2 ms so no long waiting. 地图在0.2毫秒内呈现,因此不再等待。 JSON file is also correct. JSON文件也正确。 I have no idea why javascript cannot see this method. 我不知道为什么javascript无法看到此方法。

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;
    }
}

Both file and renderTileMap aren't variables of the getData method, they are part of the context of getData (the object it is in). filerenderTileMap都不是getData方法的变量,它们都是getData (它所在的对象)上下文的一部分。 You can access the context via this so it has to be: 您可以通过this访问上下文,因此它必须是:

   $.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? 如何在回调中访问正确的“ this”?

MDN - this MDN-此

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM