Singletons and Event Arbiters

Tuesday, June 23rd, 2009 @ 1:21 pm | filed under: Best Practices, Organizing Code, Your Questions

I got an email today asking about how I use singletons in my own development environment and I thought I’d post my response for anyone who might find it useful.

Here’s the question:

Whats the best way to define some
code, assign it to a global object and have it run all at once?

I use MooTools server-side quite a bit in my ASP code using JScript
and we have need for global singleton objects to be around (such as
our logger). As there are no clear best practice ways out there of
doing it I’ve started and stuck with something like this:

var LoggerObject = function() {
// Logger code

var Logger = new LoggerObject()

which is ok but feels like I’m missing something. How do the pros do
it, whats the advantages/disadvantages to other methods?

Now, for those who aren’t familiar with the concept, a singleton is a class that designed to have only one (or, perhaps, a limited number greater than one) instance. In JavaScript, any object can inherit from any other object and you can’t really prevent this, so in the truest sense of the term, there’s no such thing as a JavaScript singleton.

MooTools gives us a function called “Class” which helps us manage inheritance between objects. Creating an object that is an instance of a class is done with the “new” operator:

[js]var myWidget = new Widget()[/js]

If you wanted to create a class and immediately cast it into an instance, you could do the following:

[js]var myInstance = new new Class({…})[/js]

The double “new” invokes the function returned by class and returns an object – an instance of that class. There’s rarely a reason to do this. In fact, the only reason I can think of is if you want that class to extend another:

[js]var myInstance = new new Class({
Extends: SomeOtherClass,
//new properties go here

The problem with this pattern is that it doesn’t really get you much. JavaScript is all about objects, and there are better ways to accomplish this task.

I use objects (as singletons) all the time for my application code (almost never for plugins obviously; those are meant to be extended and instantiated). I often use a “site” object to attach methods and manage state (such as if the user is logged in, their username, etc). I just make this a plain old JavaScript object, like so:

[js]var mySite = {
login: function(username){ this.username = username; },
showWelcome: function(){
$(‘welcome’).set(‘html’, ‘Welcome ‘ + this.username);

There’s nothing special here – this is how JavaScript works. It’s important to note that classes in MooTools exist to give us functionality and to let us derive functionality through inheritance. If I create a class called Widget and I later want to make a version called Widget.Ajax, I can extend Widget and add only the ajax parts. With singletons, the whole point is that you aren’t going to create more than one of them.

However, there are some other things that MooTools’ Class gives us, such as mixins (classes that are meant to use Implement to imbue the target class with their properties). Examples here include the Events and Options mixins that give instances methods like setOptions and addEvent. In these cases you can still use the object declaration above and then extend the object:

[js]var mySite = {
login: function(username){
this.username = username;
showWelcome: function(){
$(‘welcome’).set(‘html’, ‘Welcome ‘ + this.username);
$extend(mySite, new Events());

Working this way obviates the need for the clunky “new new Class” pattern and it’s more intelligible in my opinion.

Event Arbiters

Which brings me to a common practice I use when I build applications. When I build a site or application I try to make things as modular as possible. I make it so that my site works without any JavaScript first, then I start adding in the UI goodness with ajax and animations and sortable tables and all that jazz. I also make the JavaScript itself modular. Everything that can be a class I make a class. The stuff that’s left over is the code that instantiates those classes.

But what if the code that instantiates one widget needs to get information from another widget? For instance, what if our Welcome widget needs to know the state of the Login widget? Well, if our Login widget stores it’s state on the mySite object, then the Welcome widget can just inspect that, right? That’s cool; if the page loads and mySite.username is undefined then the Welcome widget knows the user isn’t logged in. All good.

But what happens when that state changes? What happens when the user logs in? Now we need an event – onLogin or something, but that means that Welcome needs to attach itself to Login and now we’ve lost some modularity because we’ve introduced a dependency. Welcome can’t work without Login. In this case, this doesn’t seem like a bad dependency to have – after all, a welcome message without login functionality doesn’t make much sense – but there might be dozens of other widgets that need to do things when the user logs in and we may want those widget to work even if the user doesn’t log in. Further, we may want to load the Login widget only on demand – when the user tries to log in for example. We can’t do that if all our widgets need to attach events to the Login widget.

This is why I make mySite an instance of Events. mySite doesn’t really have any native events per se. Rather, other classes attach events to it and fire events for it. So, in our puzzle above about our Login widget, instead of all the other widgets attaching an onLogin event to Login, they can attach it to mySite, and then our Login widget fires that event not on itself but on mySite:

var mySite = new Events();
var Login = new Class({
//…login logic and stuff
loginSuccess: function(username){
mySite.username = username;
var Welcome = new Class({
initialize: function(){
mySite.addEvent(‘login’, this.showMessage.bind(this));
showMessage: function(){
$(‘welcome’).set(‘html’, mySite.username ? ‘Welcome ‘ + mySite.username : ‘Please log in’);

Now our classes are no longer dependent on each other. They are both dependent on mySite but that was always the case. They can each come and go as they wish without really caring about the other. This increased modularity pays off later as your site grows in complexity. Some pages may have some widgets and some may have others. You can attach logic to the mySite object without having to really manage those dependencies.

12 Responses to “Singletons and Event Arbiters”

  1. Fabio M. Costa Says:

    Event Arbiters looks really usefull, i havent thought about that…
    Nice tip!
    About singletons i often use the plain javascript object too.

  2. Pete Duncanson Says:

    Thanks for that Aaron, cleared up the double new problem for me nicely there. I think its a nasty way of doing it simply because its too easy to miss that there are two news so could lead to alot of confusion.

    Hats off to your knowledge and the swift turn around of articles ;)

  3. davidck Says:

    Ooo, this is good (Event Arbiters). I’ve always been passing an instance of an object A to communicate with object B. The fact that modularity is improved will make widgets more re-usable.

  4. Andy Says:

    I like it :). However, as an old time C/C++ guy, I’ve got lots of red flags about the use of strings like ‘login’ in multiple places. I would normally handle this in C by using a #define. Whats the best way of handling the same thing in Javascript ?

  5. Aaron N. Says:

    This is just an example. This isn’t taken from real code I’ve authored – I just tried to think of a really simple way to illustrate the point. Given that I am NOT a C/C++ guy, what is it about ‘login’ that you find so distasteful?

  6. Andy Says:

    Only that whenever you have multiple uses of the same string somewhere, then it becomes easy to misspell on of them, of if for some reason you want to change the string due to change in functionality that would require a rename, it means you can just change it in one place, instead of multiple places. If you added a new page to your website, and typed ‘logn’ instead, how long would it take to notice find the issue?
    In C/C++, if you misspelled the #define you would get a compile time error, which means that the error would be caught much earlier ( and cheaper). One way of thinking about it is this. Say you had an event called ‘login’ that was used in 7 different files, and multiple times in some files. When you add a new openID login as well,you decide to rename the old ‘login’ event to ‘loginPassword’. Would you prefer to change it in one place, or in multiple places ? Over the years I’ve lost count the number of times things like this changed in 6 of the files, but for whatever reason the 7th file was missed.

  7. Aaron N. Says:

    Ah, well, JavaScript just doesn’t work this way. I’m not going to go into details here (it would be a long comment, for sure), but this kind of #define functionality just doesn’t exist for JavaScript (in large part because it doesn’t have a compiler – at least not in the sense that C/C++ does).

  8. Benoit Says:

    Great way of starting up an application, I like the mootools event system over many other frameworks.

    Andy, I totally agree with you, but its true javascript doesn’t has defines or constants.

    Altough you could use centralized config object to handle that sort of text keys & constants, what I’ve done in many projects. We use a config class with getters an setters for storing app constants as other various parameters (urls, etc.). We access it ine with something like this Config.get(‘LoginEventName’).
    Our object throws errors when calling undefined config key, so we are aware of typo mistakes.
    Of course you can use the singleton pattern for this if you want.

  9. Pete Duncanson Says:

    @Andy – you could do it in JS but you have to use a function to return the value. You could do it just as a variable but an mistyped variable can return null which might still get through your code, calling a non-existant function via a typo though throw an error.

    var MyEventNames = {
    login = function() { return “login”; },
    logout = function() { return “logout”; } )

    mySite.fireEvent( myEventNames.login() );

    I’m not sure if you can do the same using the $lambda function guess you could as thats what its for which would make it more readable but I’ve not used lambda much yet so could not comment but I guess it would look like this:

    var MyEventNames = {
    login = $lambda( “login” ),
    logout = $lambda( “logout” )

    @ anyone – Is the $lambda stuff right?

  10. Aaron N. Says:

    You have the $lambda stuff correct, yes.

  11. Kris Wallsmith Says:

    I’ve been using Class.Occlude and occluding to document.body when I need a singleton. Works like a charm.

  12. Aaron N. Says:

    @Kris very clever!