如何在require()之外调用require()内部定义的函数?
问题描述:
我使用ArcGIS API for Javascript 3.21。我在require()中有一个函数。我希望在单击按钮时调用该函数,但该按钮不在require()中。如何在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>
因为hello()在require()中,所以我无法在onclick =“hello()”中调用hello()。
答
您的hello函数的作用域被定义为require函数。您想将其范围限定为全局对象,即您的案例中的窗口对象。因此,要么:
function hello(){
alert("hello,world!");
}
window.hello = hello;
或直接
window.hello = function(){
alert("hello,world!");
}
但你也可以在你的Hello功能绑定到你的直接对象的JavaScript中的单击事件;你不必扩大你的功能范围。道场图书馆可能会这样做。一个直接的JavaScript的方式可能是像
var myButton = document.querySelectorAll("button.searchButton")[0];
if (myButton) {
myButton.addEventListener("click", hello);
}
+0
哇哦!我没有意识到这很简单。 – cccompro
答
你不能叫内需要的功能后使用,因为你好函数是一个匿名函数,它需要的功能运行一次里面,这是不可能恢复需要什么功能。
所以,如果你想在你需要的时候打电话给你打招呼,
答
你也可以使用Dojo模块“开”:
添加到您需要的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');
});
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript – zzzzBov