如何在 require() 之外调用在 require() 内部定义的函数?

How do I call a function that is defined inside of require() outside of the require()?

我正在为 Javascript 3.21 使用 ArcGIS API。我在 require() 中有一个函数。我希望在单击按钮时调用该函数,但该按钮在 require() 之外。

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//js.arcgis.com/3.7/js/esri/css/esri.css">
<style>
    html, body, #map {
    height: 100%;
    width: 100%;
    margin: 1;
    padding: 1; 
    }
</style>

<script src="//js.arcgis.com/3.7/"></script>
<script>

    var map;

    require([
      "esri/map", 
      "esri/geometry/Point",
      "esri/symbols/SimpleMarkerSymbol",
      "esri/graphic", 
      "esri/layers/GraphicsLayer",
      "dojo/domReady!"
    ], function(
      Map, Point, SimpleMarkerSymbol, Graphic, GraphicsLayer
    ) {
      map = new Map("map", {
      basemap: "gray",
      center: [10,10],
      zoom: 3
    });

    map.on("load", function() {
      var graphicslayer = new GraphicsLayer();
      map.addLayer(graphicslayer);
    });

   function hello(){
      alert("hello,world!");
   }   

});



</script>
</head>
<body>

    <button type="submit"class="searchButton"onclick="hello()">Search</button>
    <div id="map"></div>

</body>
</html>

我不能在 onclick="hello()" 中调用 hello() 因为 hello() 在 require() 里面。

你的 hello 函数的范围是 require 函数。您希望将其范围限定为全局对象,在您的例子中是 window 对象。所以要么:

function hello(){
    alert("hello,world!");
}   
window.hello = hello;

或直接

window.hello = function(){
    alert("hello,world!");
}

但是你也可以在javascript中直接将你的hello函数绑定到你的对象的点击事件;你不必扩大你的职能范围。在 dojo 库中可能有这样做的方法。直接的 javascript 方式可以是

var myButton = document.querySelectorAll("button.searchButton")[0];
if (myButton) {
    myButton.addEventListener("click", hello);
}

你不能在require里面调用一个函数供以后使用,因为hello函数在一个匿名函数里面,require函数只运行一次,不可能恢复require函数里面的内容。

所以,如果你想在需要时调用 hello,hello 必须在 require stament 之外。

您也可以使用 dojo 模块 "On" :

将此添加到您的 require init 中:

require([...,"dojo/on",...], function(...,on,...) {

现在编写您的事件处理程序(假设您向按钮添加了一个 ID):

<button type="submit" class="searchButton" id="searchButton">Search</button>
on(dojo.byId('searchButton'), 'click', function(evt) {
  alert('hello');
});

require({....}) 中的任何函数将对 onclick='xxx('bbb')'

不可见

你有2个选择:

1) 将此函数移到 require({....})

之外

2) 如果函数必须在 require({....}) 中,那么你必须通过(如@Nicolas 所说)

将其作为全局函数
window.xxx = function(bbb){
        alert(bbb);
}