title: javascriptMVC singleton with AJAX initializer design pattern
body: <p>I'm trying to work out the correct pattern to use for a Singleton that initializes with an AJAX call. This is a simplified example of what I have working already.</p>
  
  <p>It works as expected, but I have a feeling this is not the "correct" way and that there's some way to hook the initialiser's callback into the success call of the currently running ajax request, and I'm concerned that there could be a race condition with the array approach. Am I on the right track here?</p>
  
  <pre><code>var singletonObj;
  $.Class("SingletonTest", {
    init: function(onSuccess) {
      if (singletonObj) {
        if (singletonObj.ajaxLoaded) {
          onSuccess(singletonObj);
        }
        else {
          singletonObj.callbacks.push(onSuccess);
        }
      }
      else {
        singletonObj = this;
        singletonObj.callbacks = new Array(onSuccess);
        singletonObj.count=0;
  
        $.ajax({
          url: "/path/to/json/config",
          method: "GET",
          success: function (res) {
            singletonObj.data = res.meta_data;
            singletonObj.ajaxLoaded = true
  
            singletonObj.callbacks.forEach(function(callback) {
              callback(singletonObj);
            });
          }
        });
      }
    },
    counter: function() {
      return this.count++;
    }
  });
  
  new SingletonTest( function(obj) { console.log("First call: "+obj.counter() ) });
  new SingletonTest( function(obj) { console.log("Second call: "+obj.counter() ) });
  new SingletonTest( function(obj) { console.log("Third call: "+obj.counter() ) });
  </code></pre>
  
  <p>Or is there a simpler way to do this? What concept am I missing here that would make life easier?</p>