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 :-

[js]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;
});[/js]

This can then be used like this :-

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

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:  

2 Responses to Singletons in Dojo

  1. Johnny says:

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

  2. […] you can see in the comments, I borrowed a technique found here to make the Store a Singleton. This isn’t a robust implementation, but it works, as far as I […]

Leave a Reply

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

© 2011 Anuj Gakhar