CODE EXAMPLE
JAVASCRIPT CODE EXAMPLE: Basic JavaScript Singleton
added on Jun 8, 2012 |  VIEW EXAMPLE  | download example | permalink
Basic JavaScript Singleton
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.
 
 
<!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>
</html>
start:
continue: