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:
-
var MySingleton = new Class.Singleton({
-
initialize: function(){
-
// code here
-
},
-
method1: function(){
-
// code here
-
},
-
method2: function(){
-
// code here
-
}
-
});
Using inheritance, mixins, etc
Class.Singleton works like defining any other Mootools class using Class(), so we can have inheritance, mixins, etc.
-
var BaseClass = new Class({
-
initialize: function() {
-
// Initialization code here
-
console.log('BaseClass initialized.');
-
},
-
method1: function() {
-
// some code
-
}
-
});
-
-
var MySingleton = new Class.Singleton({
-
Extends: BaseClass,
-
initialize: function() {
-
this.parent();
-
console.log('MySingleton singleton initialized.');
-
},
-
method1: function() {
-
this.parent();
-
// more code
-
}
-
});
Hope you like it!
Repository url: http://github.com/eneko/Class.Singleton
