[英]Using callback function to change the value of a variable defined outsite of getJSON
[英]$.getJSON callback function is not defined
我正在尝试从json文件中获取数据以渲染tilemap。 但是我一直都遇到此错误Uncaught ReferenceError: renderTileMap is not defined
。
我试图将renderTileMap函数的主体放入$ .getJSON函数中,并且可以正常工作。 地图在0.2毫秒内呈现,因此不再等待。 JSON文件也正确。 我不知道为什么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;
}
}
file
和renderTileMap
都不是getData
方法的变量,它们都是getData
(它所在的对象)上下文的一部分。 您可以通过this
访问上下文,因此它必须是:
$.getJSON(this.file, this.renderTileMap);
现在,虽然现在调用了回调,但它释放了上下文,因此必须绑定它:
$.getJSON(this.file, this.renderTileMap.bind(this));
继续阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.