ArcGIS API - 调用函数 onClick()

ArcGIS API - call function onClick()

我已经设法使用 ArcGIS javascript API 让我的切片地图正常工作。但是,我希望能够切换图层(显示不同的年份)。我创建了一个函数来执行此操作:

require(["esri/map",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/geometry/Point",
    "esri/SpatialReference",
    "dojo/domReady!"],
    function (Map, Tiled, Point, SpatRef) {

... 

        function veranderTiled(jaar){
            map_Thema_2.removeAllLayers();
            tiled = new Tiled(
            "http://tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Historische_tijdreis_"+jaar+"/MapServer");
            map_Thema_2.addLayer(tiled);
        }

        ... 

    });

我想在我按页面上随机位置的按钮时调用此函数。像这样:

<input name="" type="button" onClick="veranderTiled(2015)" value="Ander jaar" />

函数本身工作正常,但我似乎无法从 require(...) 部分之外的任何地方调用它。我不确定 javascript 如何处理这种可访问性(主要用于 C++),但我确实想知道我应该更改什么以便能够从该特定脚本外部调用该函数。

编辑:正如预期的那样,未定义该函数的控制台 returns。有没有办法将它指向正确的位置(类似于 map.veranderTiled(2015)?)

这是一个范围问题 - 正如您推测的那样,该函数仅在 require 回调的范围内定义。

通常有两种方法可以解决这个问题。

首先是给按钮一个 ID 并在 require 回调中为它分配事件处理程序(假设您的脚本在 body 的末尾或者您需要 dojo/domReady!先等待正文加载):

require(..., function (...) {
    ...

    document.getElementById('veranderTiledButton').onclick = function () {
        veranderTiled(2015);
    };
});

(您也可以使用 dojo/on 来连接事件,尽管在这种情况下它并不重要。)

第二种方法是使该函数全局可用,这通常是不鼓励的,因为如果您的代码偶尔这样做,全局变量范围很快就会变成狂野的西部:

var veranderTiled; // Declare outside to be globally available

require(..., function (...) {
    ...

    // Define inside to be able to use loaded modules
    veranderTiled = function (jaar) {
        ...
    };

    ...
});