Sunday, November 21, 2010

JavaScript singleton

Following some posts on JavaScript singleton, I created the following JavaScript singleton in Tellurium IDE, which requires a singleton instance to access the Tellurium Engine.


function TelluriumFactory() {
var instance = (function() {
var _tellurium = null;
var initialized = false;

function initialize () {
_tellurium = new Tellurium();
_tellurium.initialize();
initialized = true;
}

return {
// public interface
getInstance: function () {
if(!initialized){
initialize();
}
return _tellurium;
}
};
})();

TelluriumFactory = function () {
// re-define the function for subsequent calls
return instance;
};

return TelluriumFactory(); // call the new function
}

To get the singleton instance, simply call the following method

var tellurium = (new TelluriumFactory()).getInstance();

where tellurium is a singleton.

0 comments:

Post a Comment