I have created a simple ad serving script, that you would call with global parameters, then call an external script that uses the parameters to display the adverts.
<script>
var ad_width = 100;
var ad_height = 200;
var ad_div = 'someDivID';
</script>
<script src='./js/ads.js'></script>
The ads.js has a function like:
(function(){
displayads = function(){
// do stuff here
}
displayads();
});
This works but when I have a second implementation the global variables are just over written, I need some form of encapsulation, javascript is not my foremost language so I am not sure what I am looking for.
I suppose if you want to allow multiple easy to configure ads then you could store them in an array:
var ads = [
{
width: 100,
height: 200,
div: 'someDivID'
},
...
];
Or if you think that's too hard for your customers you could allow them to write their variables like the following:
var ad1_width = 100;
var ad1_height = 200;
var ad1_div = 'someDivID';
var ad2_width = 200;
var ad2_height = 100;
var ad2_div = 'someOtherDivID';
Then in your code, you could check for their variables by checking against the window
object:
for (var i = 1; ; i++) {
var widthKey = 'ad' + i + '_width',
heightKey = 'ad' + i + '_height',
divKey = 'ad' + i + '_div';
if (window.hasOwnProperty(widthKey)) {
displayAd(window[widthKey], window[heightKey], window[divKey]);
} else {
break;
}
}
It's weird and not exactly The Right Way(tm) but it does make it easy for end users to configure. Just make sure your customers always number them sequentially if you follow that way and that they're not using any other JS that could possible use any of the same variable names.
Another possibility would be to setup a property on the window to listen for when those variables are being set:
var adWidths = [],
adHeights = [],
adContainers = [];
Object.defineProperty(window, 'ad_width', {
set: function(val) {
adWidths.push(val);
}
});
Object.defineProperty(window, 'ad_height', {
set: function(val) {
adHeights.push(val);
}
});
Object.defineProperty(window, 'ad_div', {
set: function(val) {
adContainers.push(val);
}
});
Now your customers can set their ads just by doing:
ad_width = 200;
ad_height = 100;
ad_div = 'someDivID';
ad_width = 100;
ad_height = 200;
ad_div = 'someOtherDivID';
And you can access each ad with something like:
for (var i = 0, len = adWidths.length; i < len; i++) {
displayAd(adWidths[i], adHeights[i], adContainers[i]);
}
But this does require you to run some code both before they run there's and after. This solution is not compatible with older versions of IE either.