Hi all,
There are instances where the JavaScript code for my apps becomes long and difficult to navigate. I have been exploring the option of breaking the long code out into separate JavaScript modules and loading them in through "require". However is seems like i can only return one function per module. Therefore i end up calling modules from modules.
Is this the proper way to handle this? Is there a better way to break out my code into separate files which i can then call in my main.js? For example:
I need to parse json data. Instead of having all of that code for parsing in main.js (pretend it has callbacks and more than one function), I put the json parsing code in a file called parse.js. Then from main.js I access parse.js and call its functions. like the following
parse = "./parse.js"
and then simply call
parse.parseJsonFunction(api_url)
or something along those lines.
Here is my current workflow with the AMD modules. I made the code as simple as i could. Notice how I am referencing module2 from module1. Is this how this is supposed to be done?
Index.html
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<title>
Intro to MapView - Create a 2D map | Sample | ArcGIS API for JavaScript
4.21
</title>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<link
rel="stylesheet"
/>
<script src="main.js"></script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
main.js
var loc = location.pathname.replace(/\/[^/]+$/, '');
require({
packages: [
{ name: "modules", location: loc + "/modules"}
]
},["esri/Map", "esri/views/MapView","modules/module1"], (Map, MapView, module1) => {
const map = new Map({
basemap: "topo-vector"
});
const view = new MapView({
container: "viewDiv",
map: map,
zoom: 4,
center: [15, 65] // longitude, latitude
});
var value_from_modules = module1.myfunction(5, 5)
alert(value_from_modules)
});
module1.js
define(
["./module2"],
function(module2) {
return {
myfunction: function(a,b) {
alert("entered module1")
var add = module2.add(a,b)
return add;
}
}
}
)
module2.js
define(
[],
function() {
return {
add: function(a,b) {
alert("entered module2")
return a + b;
}
}
}
)