Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8148865
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T14:43:48+00:00 2026-06-06T14:43:48+00:00

I’m trying to work out the correct pattern to use for a Singleton that

  • 0

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.

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?

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() ) });

Or is there a simpler way to do this? What concept am I missing here that would make life easier?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T14:43:49+00:00Added an answer on June 6, 2026 at 2:43 pm

    Since you’re looking the “correct” way here are some general notes:

    1. You don’t need a class for a singleton (JavaScript isn’t Java). Just make it a global obj or better yet a function.

    2. $.Deferred is your friend. $.ajax returns a promise.

    Here is a functional pattern for singletons:

    // creates a lazy singleton from a factory function
    function singleton(factory) {
        var deferred;
        return function() {
            return deferred || (deferred = factory());
        };
    }
    
    // declare your specific singleton
    var SingletonTest = singleton(function() {
        return $.ajax({
            url: "/path/to/json/config",
            method: "GET"
        }).pipe(function(obj) {
            // pipe lets you modify the result
            // here we add the counter method
            var count = 0;
            obj.counter = function() {
                return count++;
            };
            return obj;
        });
    });
    
    // use it
    SingletonTest().then(function(obj) {
        console.log("First: "+obj.counter());
    });
    
    SingletonTest().then(function(obj) {
        console.log("Second: "+obj.counter());
    });
    

    If you find yourself using this pattern a lot, there is a JMVC plugin (disclosure: I’m the primary author) that implements a functional form of dependency injection.

    If you were to use Inject, it would look like this:

    var cache = Inject.cache();
    var Injector = Inject(
        cache.def('SingletonTest',function() {
            return $.ajax({
                url: "/path/to/json/config",
                method: "GET"
            }).pipe(function(obj) {
                var count = 0;
                obj.counter = function() {
                    return count++;
                };
                return obj;
            });
        })
    );
    
    var logCount = Injector('SingletonTest',function(obj,message) {
        console.log(message+obj.counter());
    });
    
    logCount("First:");
    logCount("Second:"); 
    

    For large projects with a lot of singletons or just deferred data, injecting scales better than global variables.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.