正在使用异步请求初始化对象
Initializing object with asynchonous request
这是我的对象定义:
function DrilledLayer(sourceLayerName, sourceTableName, targetLayerName, targetFieldName, operators, baseLayer=false) {
this.sourceLayerName = sourceLayerName;
this.sourceTableName = sourceTableName;
this.targetLayerName = targetLayerName;
this.targetFieldName = targetFieldName;
this.operators = operators;
this.baseLayer = baseLayer;
this.targetLayerId;
this.drilledLayerId;
this.selectedCode;
this.redraw = false;
this.getTargetLayerId(); //this function must initialize this.targetLayerId
}
DrilledLayer.prototype.getTargetLayerId = function(){
$.soap({
url: 'https://url/version_4.8/services/MapService',
method: 'getLayersIdByName',
appendMethodToURL: false,
data : {
mapInstanceKey: mapKey,
layerName: this.targetLayerName,
},
error: function(){
alert("error getLayersIdByName");
},
success: function(soapResponse){
layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
this.targetLayerId = layerId;
}
});
}
这就是我创建对象的方式:
drillCs = new DrilledLayer("Drilled CS", "Cs_Franco_General.TAB", "RA_General", "Code_RA", "=")
如果我查看drillCs对象,则没有定义targetLayerId属性,但我知道soap请求已成功发出。为什么?
this
主要由函数的调用方式设置。success
回调期间的this
与调用getTargetLayerId
函数时的this
不同,您必须记住
在这种情况下,最简单的方法可能是使用一个变量:
DrilledLayer.prototype.getTargetLayerId = function(){
var layer = this; // <=== Set it
$.soap({
url: 'https://url/version_4.8/services/MapService',
method: 'getLayersIdByName',
appendMethodToURL: false,
data : {
mapInstanceKey: mapKey,
layerName: this.targetLayerName,
},
error: function(){
alert("error getLayersIdByName");
},
success: function(soapResponse){
layerId = soapResponse.toJSON().Body.getLayersIdByNameResponse.getLayersIdByNameReturn.getLayersIdByNameReturn.text;
layer.targetLayerId = layerId; // <=== Use it
}
});
}
更多(在我的博客上):
- 你必须记住
this
当然,另外,在异步回调触发之前(这将是new
调用返回后的一段时间),您不会看到正确的,但您似乎对异步方面感到满意。
相关文章:
- 使用javascript函数在页面初始化后加载jquery
- 未捕获错误:无法在初始化之前调用方法;
- 如何在剑道网格初始化后设置pageSizes
- React redux初始化功能,无论状态变化如何
- 为什么可以't Protractor在自动初始化的Angular网站上查找Angular
- 尝试初始化()Spine's控制器和故障
- Angular.js延迟控制器初始化
- 对插件初始化后动态加载的元素进行样式设置
- Angular JS控制器初始化错误
- 在XMLHttpRequest之后重新初始化jQuery
- 在初始化路由之前发送$http请求
- $http AngularJS 应用程序初始化之前的请求
- SCRIPT5022:集合尚未初始化.尚未请求或请求尚未执行
- 通过 ajax 请求初始化控制器
- 正在使用异步请求初始化对象
- 用几个ajax请求初始化控制器的最佳方式
- 由于IMG元素中SRC属性的值未初始化,避免了多个GET请求
- 在ajax请求后重新初始化processing.js草图
- 数据表初始化ajax请求初始值
- 在Ajax请求后重新初始化AngularJs(动态内容)