I have created a JavaScript/jQuery widget which needs to have the ability to be embedded in pages multiple times, each with their own variables set differently. At the moment various variables are being over written by whichever widget loads last.
Here is a cut down version for example purposes.
(function () {
var scriptName = "my.widget.js";
var TGW;
var jqueryPath = "https://ajax.googleapis.com/yada_yada...";
var scriptTag;
var jScript;
/******** Get reference to self (scriptTag) *********/
var allScripts = document.getElementsByTagName('script');
var targetScripts = [];
for (var i in allScripts) {
var name = allScripts[i].src
if(name && name.indexOf(scriptName) > 0)
targetScripts.push(allScripts[i]);
}
scriptTag = targetScripts[targetScripts.length - 1];
/******** Set jQuery noConflict *********/
if (window.TGW === undefined || window.TGW.fn.jquery !== jqueryVersion) {
loadScript(jqueryPath, initTGW);
} else {
initTGW();
}
function initTGW() {
TGW = window.jQuery.noConflict(true);
main();
}
function main() {
TGW(document).ready(function ($) {
loadParams();
});
}
function loadParams() {
jScript = TGW(scriptTag);
comments = jScript.data("comment");
}
})();
And here is how it is added to the webpage twice with different settings for the comment data attribute.
<script src='https://...my.widget.js' data-comment='yes'></script>
<script src='https://...my.widget.js' data-comment='no'></script>
With the above, if there is a hypothetical button in the widgets which displays the contents of the variable comments
, the variable will randomly contain/display "yes" or "no" depending on which widget loaded last.
What needs to happen when the button on the first widget is pressed, is it display "yes". And when the button on the second widget is pressed, it display "no".
I think this is to do with namespaces or something, but I don't really understand it. I thought wrapping the entire widget in (function () {
made in run as an anonymous function which would mean all the variables are separate.
Any help appreciated