2017-08-14 5 views
-2

私は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()を呼び出すことはできません。

+0

https://en.wikipedia.org/wiki/Unobtrusive_JavaScript – zzzzBov

答えて

1

hello関数のスコープは、require関数です。あなたはあなたのケースのウィンドウオブジェクトであるグローバルオブジェクトにスコープしたいと思う。だから、次のいずれか

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

または直接

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

しかし、あなたはまた、JavaScriptで直接あなたのオブジェクトのクリックイベントにごハロー機能を結合することができます。あなたの機能の範囲を広げる必要はありません。 dojoライブラリーでそうする方法があります。こんにちは関数は関数が一度に実行必要匿名関数、内部にあるので、直接のjavascriptの方法は、後で使用するために必要な内部の関数を呼び出すことはできません

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

すごいああ!私はそれがそれほど単純ではなかったことを理解していません – cccompro

0

ようなものになる可能性があり、回復することはできません必要な機能の中身は何ですか?

あなたが必要なときにhelloを呼び出すには、helloがrequire stamentの外にある必要があります。

ます。また、「オン」道場モジュールを使用することができ
0

をあなたの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'); 
}); 
関連する問題