Singletons in Dojo

On August 29, 2013, in Javascript, by Anuj Gakhar

I’ve been working with Dojo Toolkit for the past few months and I have started to like it actually. It is a full featured stack that includes core DOM manipulation, selectors, widgets, unit testing framework, build scripts, charting etc all combined into one big library. I just think it is not as widely as it should be.

Anyways, coming to the point of this post, I wanted to write a Singleton Class using Dojo’s declare. There is apparently a very interesting thread on Stackoverflow here on this very subject.

I ended up using this approach below :-

define([
    "dojo/_base/declare",
], function(
    declare
) {
    var SingletonClass = declare("com.my.package.SingletonClass", [], {
        doSomething: function(arg1) {
            return "hello";
        }
    });
    if (!_instance) {
        var _instance = new SingletonClass();
    }
    return _instance;
});

This can then be used like this :-

define([
    "dojo/_base/declare",
    "com/my/package/SingletonClass"
], function(
    declare,
    SingletonClass 
) {
    return declare(null, {
      SingletonClass.doSomething(); //can be called without using the 'new' operator
   });
});

Some might argue that a Singleton pattern must have a getInstance() method and actually one of the solutions in the SO thread above does do exactly that too. Would love to hear what people think about this and if anyone’s got a better implementation of this?

Tagged with:  

One Response to Singletons in Dojo

  1. Johnny says:

    Nice and simple and works well. Thanks… This approach in now in my app.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: