如何在 require() 之外调用在 require() 内部定义的函数? [英] How do I call a function that is defined inside of require() outside of the require()?

查看:37
本文介绍了如何在 require() 之外调用在 require() 内部定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using ArcGIS API for Javascript 3.21. I have a function inside of the require(). I want the function to be called when a button is clicked, but the button is outside the 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() 中.

I can't call hello() in onclick="hello()" because hello() is inside the require().

推荐答案

你的 hello 函数的作用域是 require 函数.您希望将其范围限定为全局对象,在您的情况下是窗口对象.所以要么:

Your hello function is scoped to the require function. You want to scope it to the global object, which is the window object in your case. So either:

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

或直接

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

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

But you could also bind your hello function to the click event of your object directly in javascript; you don't have to widen the scope of your function. There is likely methods to do so in the dojo library. A direct javascript way could be something like

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

这篇关于如何在 require() 之外调用在 require() 内部定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆