Skip to content

Instantly share code, notes, and snippets.

@jasonwyatt
Created July 26, 2011 15:09
Show Gist options
  • Save jasonwyatt/1106973 to your computer and use it in GitHub Desktop.
Save jasonwyatt/1106973 to your computer and use it in GitHub Desktop.
Singleton Pattern with Require JS
define(function(){
var instance = null;
function MySingleton(){
if(instance !== null){
throw new Error("Cannot instantiate more than one MySingleton, use MySingleton.getInstance()");
}
this.initialize();
}
MySingleton.prototype = {
initialize: function(){
// summary:
// Initializes the singleton.
this.foo = 0;
this.bar = 1;
}
};
MySingleton.getInstance = function(){
// summary:
// Gets an instance of the singleton. It is better to use
if(instance === null){
instance = new MySingleton();
}
return instance;
};
return MySingleton.getInstance();
});
@jasonwyatt
Copy link
Author

Posted this on my blog: http://blog.jwf.us

@Nek
Copy link

Nek commented Feb 18, 2013

nice. thanks!

@timboudreau
Copy link

Wow, this looks like Java code in Javascript :-)

I don't believe there is any difference at all between this rather verbose code and

return {
    initialize: function(){
        this.foo = 0;
        this.bar = 1;
    }
};

If define() is actually called twice above, your object is not a singleton (var instance is not shared across multiple invocations). Just as if the above line of code is called twice, you don't have a singleton. Ergo, they are 100% equivalent.

@wilmoore
Copy link

wilmoore commented May 9, 2013

I do not think his use-case is to call define more than once...his calling code will likely look like var singleton = require('mysingleton').

That being said, you are also correct in that all of the extra boilerplate may not have been necessary since he is exporting only the retrieved instance. His constructor guards would be useful only if he were exporting MySingleton itself.

@aoberoi
Copy link

aoberoi commented Jul 3, 2013

@timboudreau 👍

The crux of this suggestion is that define() won't run the module creation function more than once, it already caches the return value. Caching theInstance is extraneous.

@thataustin
Copy link

@aoberoi, I think I may be re-stating what you said, but this whole gist is unnecessary, right? I'm under the impression that require js will only define each module once and returned the cached module every time thereafter (allowing you to treat it as a singleton if you'd like to, maybe using a closure to update singleton state if you need to). If that's the case, why would you need to try to enforce a singleton pattern?

@lagden
Copy link

lagden commented Jun 16, 2014

@herebebeasties
Copy link

This looks like an attempt to give you a lazy singleton, but it actually then goes and instantiates it before returning, rendering all the getInstance stuff redundant.

@jt000
Copy link

jt000 commented Aug 20, 2014

Singletons are actually very easy using require. Just return the instance in your define. Personally, I like to go with this pattern: http://jsfiddle.net/jaytre/xLj1uw3r/

@herebebeasties - Require handles the laziness. The singleton won't be created until the first time require(['mySingleton'], ...) is called.

@lagden
Copy link

lagden commented Nov 11, 2014

pretty interesting @jt000!!

@layton-glympse
Copy link

layton-glympse commented May 16, 2016

@jt000 but that's not a singleton. The concept of a singleton is that you can't make individual instances of it. Or am I missing something from your example? All you're doing there is making a second require that I have to import to provide the illusion of a singleton.
Imagine doing that for 50 classes in a project. You all of a sudden have 100 defines...

@layton-glympse
Copy link

layton-glympse commented May 16, 2016

@jasonwyatt Out of curiosity, is there a reason that getInstance is even necessary? Why can't we just have the constructor point to _instance and return that if it's not null? I.e., here is my revised version that seems to return the same object every time. Note that it makes use of the fact that you can use a constructor to return anything you want.

define(function(require, exports, module)){
    var _instance = null;

    function MySingleton() {
        //You can retrofit this to support calling init() where necessary... just keeping it brief :)
        _instance = _instance === null ? this : _instance;
        return _instance;
    }

    module.exports = MySingleton;
});

Seems to work for me... any reason you think this wouldn't be equivalent output-wise to yours? The upside to this is that it conforms more to the requirejs ecosystem and is easier to read.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment