如何在require()之外调用require()内部定义的函数? [英] How do I call a function that is defined inside of require() outside of the require()?
问题描述
我正在使用Java API 3.21的ArcGIS API.我在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屋!