Reputation: 3
I will appropriate your help in creating my library in JavaScript and using Dojo. It seems to me like a beginner problem but I can't seem to find the problem.
I am trying to create a library that is named 'edm'
The EDM.js is very simple:
define([
"dojo/_base/declare"
], function(declare) {
var EDM = declare("EDM", {
constructor: function() {
console.log("Hi EDM lib")
},
sayHi: function() {
console.log("Hi EDM lib")
}
});
edm = new EDM();
return edm;
});
The index.html to load it:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js"
data-dojo-config="async: true"></script>
<script src="../src/EDM.js" type="text/javascript"></script>
</head>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
and the main.js to use the edm is:
var newObject = edm;
The idea is basically to be able to use edm as prefix for the functions in EDM.js file.
However, when loading the index.htm file I get this error: "Uncaught ReferenceError: edm is not defined"
I will appropriate any direction.
Thanks
Upvotes: 0
Views: 108
Reputation: 44685
You should use the Dojo AMD loader in stead of loading the file yourself. Remove the following <script>
tag:
<script src="../src/EDM.js" type="text/javascript"></script>
Then write the following code in main.js
:
require([ "../src/EDM" ], function(edm) {
var newObject = edm;
});
The advantages of doing it this way is the following:
<script>
tags that slow down the page when loadingOf course, because no objects are on global scope, you cannot retrieve the edm
object directly. That's why you got that ReferenceError
.
To answer your question from the comments: yes and no. Actually, you're already adding edm
to the global scope in EDM.js
because you didn't put var
in front of the following statement:
edm = new EDM();
However, the define()
callback is only executed if it's called from the Dojo AMD loader inside a require()
function. So that actually means that you have to load the AMD module first and then you will be able to access edm
from global scope.
So in your case, the following will work as well:
require([ "../src/EDM" ], function(bla) {
var newObject = edm;
});
As you can see in the example above, we call our module bla
, however, because you added it to global scope in EDM.js
, it's now available. But, in order to add it to the global scope you have to properly load the module.
But be careful, adding objects to global scope is usually not encouraged, because they can be manipulated from any code which makes it hard to debug. There are a lot of other reasons why global variables are not a good idea, you can probably find a lot more information about it on the web.
Upvotes: 1