I get my javascript loaded in an undetermined order. I have a namespace function to register namespaces. For example it’s possible to write something like this:
"com.stackoverflow.question".namespace(new function() {
this.sayHelloTo = function(text) { alert("Hello" + text); }
});
Unfortunately the namespace.js isn’t always loaded first, as the loading order is random but the other scripts make use of the namespace function. Is there a way to achieve this without getting the error “.namespace” ist not a function?
So there must be a way to initialize the sayHelloTo definition later, I have an everything is loaded event. So the upcoming statement works but it’s very ugly I think.
var postInit = postInit || [];
postInit.push(function() {
"com.foo.bar".namespace(new function() {
this.sayHelloTo = function(text) { alert(text); }
});
});
And when the event occurs:
list.foreach(function(k, v) { v.call(); });
Is there any better way to achieve this?
Use AMD: take a look at http://requirejs.org/. Alternately common.js may work depending on the use.