I’m having trouble figuring out how to handle multiple instances of some javascript functions that I want to run on a page. It’s part of a custom analytics project that I’m working on.
I have a function called initData(); The function uses a setInterval to call another function that sends a ping to my server every 1000ms.
The problem is that I want to be able to have more than one instance of this function on a single page. My current problem is that as soon as the second instance is called it overwrites all the variables from the first.
What’s the best way to get around this? Is there a way to make the functions seperate and/or private instances so that they don’t interfere with each other?
By default all variables (and therefore also function declarations) live in the global namespace.
The only way to introduce a separate namespace in javascript is with a function call. This is how you do that:
You wrap your stuff in an anonymous function, and then call it immediately. This way your functions will be separate, even with the same name.
Example
So, for instance, if you have code like this:
and you have someplace else:
then one
initDatawill overwrite the otherinitData. However, if you wrap each in its own(function () {}());then they will be separate.Be aware though, that these names are no longer in the global namespace, so they are also not available for use outside of the anonymous function.
One global
To control how much and what you expose in the global namespace, it is custom to expose what you need through one global object, usually in all capital letters.
You would do this by making sure FOO exists, and if it doesn’t: create it.
The same for your module namespaces:
and then inside of the anonymous function, expose what you want.
Complete example
module1.js:
module2.js:
controller.js:
A last tip
The controller like written is dependent on both
module1.jsandmodule2.jsand needs to be loaded last. That can be avoided using something likejQuery‘sdocument.ready, making it wait for all scripts to load.If you’re not already using jQuery, you can use a small script like domReady to avoid the bloat.