gpt4 book ai didi

javascript - Dojo - Promise 无法访问变量

转载 作者:行者123 更新时间:2023-11-29 16:09:47 25 4
gpt4 key购买 nike

我在 ESRI Web App Builder 中使用 dojo,遇到过这样的情况:我需要运行 AJAX 调用并仍然访问基类中的变量。下面是我的代码,其中包含注释,以准确解释它成功的地方和失败的地方:

define(['dojo/_base/declare', 'jimu/BaseWidget', 'dojo/request', "esri/layers/WMSLayer", "esri/config", "dojo/domReady!"], function (declare, BaseWidget, request, WMSLayer, esriConfig) {

return declare([BaseWidget], {
baseClass: 'jimu-widget-mywidget',
// This function is called by a button press (Normally the WMSLayer variable would be set by user input)
addWms: function () {
var wmsLayer = new WMSLayer("http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer", {
format: "png",
visibleLayers: [2]
});

this.map.addLayer(wmsLayer); // this.map is inherited from BaseWidget as far as I can see. This adds a wms to my map without error

request("request.html").then(function(data){
var wmsLayer = new WMSLayer("http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer", {
format: "png",
visibleLayers: [2]
});

this.map.addLayer(wmsLayer); // This is now in another context....I get the error HERE.
// At this point map is not defined because this anonymous function is running
// in a different context. ( at least I think that's what is happening )
}, function(err){
// Hopefully there are no typos in my example XD
});
}
});
});

我的问题是 --> 如何使用“request”的回调函数访问“map”变量?

我希望能够通过调用 WMS 服务的 GetCapabilities 来运行 this.map.addLayers。请求通常会调用它,我一直走到代码的末尾,直到我无法再访问“map”变量为止。

首选 Dojo 类型的答案,但普通的旧 javaScript 也可以。请避免使用 JQuery 答案。

资源是:
ESRI JavaScript library
Dojo
ESRI Web App Builder

最佳答案

您遇到的问题是调用异步回调时丢失执行上下文的经典问题(因此 this 不再意味着您想要的)。通常有两种方法可以解决此问题。

一种方法是在外部作用域中创建一个引用this 的变量,以便内部函数可以访问它:

var self = this;
request('request.html').then(function (data) {
// ...

self.map.addLayer(wmsLayer);
});

另一种方法是使用上下文绑定(bind),通过 Function#bind (ES5) 或 dojo/_base/lang.hitch:

// Function#bind:
request('request.html').then(function (data) {
// ...

this.map.addLayer(wmsLayer);
}.bind(this));

// lang.hitch:
request('request.html').then(lang.hitch(this, function (data) {
// ...

this.map.addLayer(wmsLayer);
}));

将异步处理函数分解为另一个内部实例方法的绑定(bind)方法也很常见:

_addRequestedLayer: function () {
// ...

this.map.addLayer(wmsLayer);
},

addWms: function () {
// ...

// ES5:
request('request.html').then(this._addRequestedLayer.bind(this));
// ...or lang.hitch, with late binding:
request('request.html').then(lang.hitch(this, '_addRequestedLayer'));

还有一个tutorial on lang.hitch .

关于javascript - Dojo - Promise 无法访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com