Using the Singleton Pattern in RequireJS

Using the singleton pattern in your RequireJS app has its advantages, below is a very simple implementation, enjoy :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
define([],

    function() {

        'use strict';
    
        var instance = null;
 
        function Singie() {
            if(!!!instance){
                this.initialize();
                instance = this;
            }
            window.SINGIE = instance; // Good to have reference on window
            return instance;
        };

        Singie.prototype = {
            initialize: function() {
                // Private vars
                this._hello = 'Hello';

                // Public methods
                this.sayHello = function sayHello(name) {
                    var n = name || 'Anonymous';
                    console.log(this._hello + ' ' + n);
                }
            }
        };

        return Singie;
    }
);

The above code lets you use one single instance of the ‘Singie’ module, as it always will return its sole instance - no matter how many times you instantiate it.

An example of accessing the public methods of the singleton instance:

1
2
3
4
var singie = new Singie();
singie.sayHello('Foo');

// Will put 'Hello Foo' in the console

And here is a quick test to see if there is no cheekiness, and there is indeed only once instance existing:

1
2
3
4
5
var singie = new Singie();
var singieClone = new Singie();
console.log(singie === singieClone);

// Will put true in the console

Having a reference on the ‘window’ object can also come handy:

1
2
3
4
var singie = new Singie();
SINGIE.sayHello('Bar');

// Will put 'Hello Bar' in the console

That’s all folks!

Comments