我希望main.js从map.js调用makeAMap(),但是makeAMap()包含在“ require”语句中,这确实给我带来了困难,我什至尝试将其全局化。最初的问题似乎只是该函数加载太晚,但是在尝试了回调和函数包装器之后,我认为这是时间和“要求”的综合问题。现在,我已经找到一种解决方法,但是我宁愿main.js运行该方法。
我尝试了回调,函数包装,各种全局和窗口变量以及$ .getScript。 map.js首先导入html。 我发现了这个类似的帖子 How to call function from another file with requireJS 但它似乎朝着相反的方向发展,我认为我无法应用该解决方案。还有另一个类似的问题 How do I call a function that is defined inside of require() outside of the require()? 但是答案与按钮/事件更多有关,并不能真正帮助我。
//map.js
makeAMap = function (mapBasemap) {}; //a global function
loadTheMapController = function(){
require([
"esri/Map",
"esri/views/MapView"
], function (Map, MapView) {
makeAMap = function(mapBasemap){ //overrides the global function
var theMap = new Map({
basemap: mapBasemap
});
return theMap;}
console.log(makeAMap); //displays the correct function after loadTheMapController is called
}//end loadTheMapController wrapper
//main.js
console.log(makeAMap); //displays the empty global function
loadTheMapController();
console.log(makeAMap); // still displaying empty global function
//even tried this
$.when(loadTheMapController()).then(console.log(makeAMap));
//returns the empty function like it wasn't overwritten
或者只是测试全局变量是否被覆盖
//map.js
var makeAMap;
$(document).ready(function () {
require([
"esri/Map",
"esri/views/MapView"
], function (Map, MapView) {
makeAMap = function(mapBasemap){
var theMap = new Map({
basemap: mapBasemap
});
return theMap;
}
console.log(makeAMap); //returns the correct function
}//end of doc.ready
console.log(makeAMap); //returns undefined
我想我在这里遇到多个问题,第一个问题是我的全局函数没有被覆盖。对不起,分层问题。你觉得呢?