having fun with code

Finally: Singletons, the Mootools way

I have been using for a while the “new new Class” syntax to create singletons on the projects I am working on. This is for many reasons, but specially because I didn’t like other solutions like Class.Mutators, Class.Oclude or extending a plain object with $extend().

Now, after discussing a little bit on the Mootools email list about what was the best way to create singletons, I have created Class.Singleton so we can create singletons the Mootools way. Here is how it works:

  1. var MySingleton = new Class.Singleton({
  2.     initialize: function(){
  3.         // code here
  4.     },
  5.     method1: function(){
  6.         // code here
  7.     },
  8.     method2: function(){
  9.         // code here
  10.     }
  11. });

Using inheritance, mixins, etc

Class.Singleton works like defining any other Mootools class using Class(), so we can have inheritance, mixins, etc.

  1. var BaseClass = new Class({
  2.     initialize: function() {
  3.         // Initialization code here
  4.         console.log('BaseClass initialized.');
  5.     },
  6.     method1: function() {
  7.         // some code
  8.     }
  9. });
  10.  
  11. var MySingleton = new Class.Singleton({
  12.     Extends: BaseClass,
  13.     initialize: function() {
  14.         this.parent();
  15.         console.log('MySingleton singleton initialized.');
  16.     },
  17.     method1: function() {
  18.         this.parent();
  19.         // more code
  20.     }
  21. });

Hope you like it!

Repository url: http://github.com/eneko/Class.Singleton

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation