I needed a singleton in JavaScript in order to make a DataManager which is called multiple times, but I just want it to load its data only the first time it is called, then give pieces of the data out view public methods, never loading the initial data again.
I found a number of approaches to building singletons in JavaScript but this one seems to have everything I need.
Does anyone see any kind of problem this singleton is going to have for the uses I need it for?
<!DOCTYPE html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>