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:
var myWidget = new Widget()
If you wanted to create a class and immediately cast it into an instance, you could do the following:
var myInstance = new new Class({...})
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:
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:
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:
var mySite = {
login: function(username){
this.username = username;
this.fireEvent('login');
},
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;
mySite.fireEvent('login');
}
});
var Welcome = new Class({
initialize: function(){
this.showMessage();
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.