使用异步请求初始化对象

时间:2014-10-10 13:28:26

标签: javascript

这是我的对象定义:

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请求已成功完成。为什么呢?

1 个答案:

答案 0 :(得分:2)

JavaScript中的

this主要由函数的调用方式决定。 this回拨期间的success在您致电this功能期间与getTargetLayerId不一致,您必须记住它。

在这种情况下,最简单的方法可能是变量:

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

更多(在我的博客上)

另外,当然,在异步回调触发之前(在new调用返回之后的某个时间),您将无法正常查看,但您似乎对异步方面感到满意此