Finally: Singletons, the Mootools way

Jan 18 2010 Published by Eneko Alonso under uncategorized

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

No responses yet

Sending messages between Javascript objects

Apr 23 2009 Published by Eneko Alonso under uncategorized

When applications (or websites) get pretty big, it usually happens that a lot of different objects or classes interact with each other or, even worst, depend on each other to achieve the site functionality.

A simple example could be a Tabs manager class, which controls a set of tabs in the page. Sometimes, the content in this tabs is sensitive to when the tabs are shown or hidden. At this point you have three options: either the Tabs class needs to know about the content or you create a set of callback functions or you use custom events. Still, for every one of these options you are going to need variables referencing the instances of your classes (this is: var myTabs = new Tabs())

Personally, I don’t like having global variables for the objects I create. I think the code gets very messy and complicated.

So, after dealing with all these issues at work day after day I thought it would be very cool to have a messaging system between my classes, the same way other languages like Cocoa do (in a more simpler way, at least for now).

Sending messages between classes

Wouldn’t it be nice if the Tabs class would send a message every time a new tab is selected? Wouldn’t it be nice if the objects that are going to reside inside those tabs could listen to that message and update accordingly?

To do this, I created a Base class and a Register, where my objects will register automatically upon instantiation (thanks to the Base class).

  1. var InstanceRegister = new Class({
  2.   instances: [],
  3.   addInstance: function(object) {
  4.     this.instances.push(object);
  5.   },
  6.   broadcastMessage: function(msg) {
  7.     $A(this.instances).each(function(item, index) {
  8.       item.processMessage(msg);
  9.     });
  10.   }
  11. });
  12. var Register = new InstanceRegister();
  13.  
  14. var Base = new Class({
  15.   ClassName: 'Base',
  16.   Implements: Options,
  17.   initialize: function(options) {
  18.     this.setOptions(options);
  19.     Register.addInstance(this);
  20.   },
  21.   processMessage: function(msg) {
  22.     console.log(this.ClassName, ' msg received: ');
  23.     console.dir(msg);
  24.   },
  25.   sendMessage: function(msg) {
  26.     Register.broadcastMessage(msg);
  27.   }
  28. });

As you can see, the register is just an array of Instances. Yes, Register is a global object, but it will be the only one we will need. Meanwhile, the Base class adds the new instance to the Register automatically. For convenience, the Base class has a sendMessage method. Also, for convenience, I like to add a ClassName property to all my classes in case I need it later for logging, instance class type identification, etc.

Now, thanks to MooTools, we can create our classes and make them inherit from Base. We can override the processMessages method and act accordingly:

  1. var Tabs = new Class({
  2.  ClassName: 'Tabs',
  3.  Extends: Base,
  4.  …
  5.  activateTab: function(tab) {
  6.   …
  7.   this.sendMessage({msg:'tabActivated', data:tab});
  8.  }
  9. });
  10.  
  11. var VideoPlayer = new Class({
  12.  ClassName: 'VideoPlayer',
  13.  Extends: Base,
  14.  …
  15.  processMessage: function(msg) {
  16.   if (msg.msg == 'tabActivated' && msg.data = 'video-tab') {
  17.    // Play video
  18.   }
  19.  }
  20. });

The beautifulness of this code resides, as I mentioned before, in the absence of any object references. Tabs doesn’t know anything about the VideoPlayer class nor any other object listening to the messages. And the VideoPlayer doesn’t know anything about the Tabs class either. It only knows about the message it has to listen to. No object references, no methods, no callbacks.

Pay attention now. This is the best part! Whenever we instance our classes, no matter how many times we do, we don’t need variable references anymore:

  1. new Tabs();
  2. new VideoPlayer();

Nice, uh?

Since I implemented this class I use it a lot on every project at work. It makes my life easier, keeping my classes simple and independent from each other. It’s even better. We have got to a point where we have integrated this feature with our Flash components, so these send messages to the Register when needed and any JS object listening reacts to them as needed.

By doing this, even being unidirectional (Flash to JS only), we have achieved something great: from now on, our Flash objects don’t need to know anything about our JS objects at all. Just send a message to the register and done.

At any point, even from Firebug, you can send a message to the Register. This is very nice, even for debugging:

  1. Register.broadcastMessage({msg:'hello',data:'world'});

A listener class

I found it is very nice, while in development, to have a Listener class debugging any message received. This way I don’t need to add a console.log call on all my classes to output received messages. The Listener will do it for me:

  1. var Listener = new Class({
  2.  Extends: Base,
  3.  initialize: function() {
  4.   this.parent();
  5.   this.ignoreMessages = false;
  6.  },
  7.  processMessage: function(msg) {
  8.   if (msg.msg == 'stopListener') this.ignoreMessages = true;
  9.   if (msg.msg == 'startListener') this.ignoreMessages = false;
  10.   if (this.ignoreMessages) return;
  11.   console.log('Listener: msg received:');
  12.   console.dir(msg);
  13.  }
  14. });
  15. new Listener();

Even you can control the Listener by sending custom messages to it! Awesome!

Could this be achieved with custom events?

With Mootools, creating custom events is piece of cake. But from what I understand, custom events work only inside the object that is firing them. This is, if object A fires an event ‘customEvent’, you can only listen to it if you add a callback function when you instantiate that class:

  1. var A = new Class({
  2.   Implements: Events,
  3.   initialize: function() {
  4.     document.body.addEvent('click', function() {
  5.       console.log('A: body clicked');
  6.       this.fireEvent('bodyClicked', [this]);
  7.     }.bind(this));
  8.   }
  9. });
  10.  
  11. var B = new Class({
  12.   doSomething: function() {
  13.     console.log('B: doing something…');
  14.   }
  15. });
  16.  
  17. new A({
  18.   onBodyClicked: function() {
  19.     // Tell B to do something (you need a reference to B!)
  20.   }
  21. });
  22. new B(); // Will never do something

Ideally, B should be able to listen to the bodyClicked event without passing any info when A is instantiated. But if I’m not mistaken, this is not possible.

Revised version

I decided that it would be cool to have the Messenger as something my classes could implement, instead of inherit from (Base). Also, it would be good if one object could register for a specific message only, which would improve performance too.

  1. var NotificationServiceCenter = new Class({
  2.  instances: {},
  3.  addObserver: function(msg, instance) {
  4.   if (!this.instances[msg]) {
  5.    this.instances[msg] = [];
  6.   }
  7.   this.instances[msg].push(instance);
  8.  },
  9.  broadcastMessage: function(msg, data) {
  10.   if (this.instances[msg]) {
  11.    $A(this.instances[msg]).each(function(item, index) {
  12.     item.processMessage(msg, data);
  13.    });
  14.   }
  15.  }
  16. });
  17. var NotificationService = new NotificationServiceCenter();
  18.  
  19. var Messenger = new Class({
  20.  addMsgEvent: function(msg) {
  21.   NotificationService.addObserver(msg, this);
  22.  },
  23.  sendMessage: function(msg, data) {
  24.   NotificationService.broadcastMessage(msg, data);
  25.  },
  26.  processMessage: function(msg, data) {
  27.   // For implementation on the final Class
  28.  }
  29. });
  30.  
  31. var A = new Class({
  32.  Implements: Messenger,
  33.  initialize: function() {
  34.   document.body.addEvent('click', function(){
  35.    console.log('A: document body clicked');
  36.    this.sendMessage('documentbodyclicked', 'Hello world!');
  37.   }.bind(this));
  38.  }
  39. });
  40.  
  41. var B = new Class({
  42.  Implements: Messenger,
  43.  initialize: function() {
  44.   this.addMsgEvent('documentbodyclicked');
  45.  },
  46.  processMessage: function(msg, data) {
  47.   console.log('B: msg received: ', data);
  48.  }
  49. });
  50.  
  51. new A();
  52. new B();

Here you go!

2 responses so far

Setting up timers and intervals inside JS objects

Apr 07 2009 Published by Eneko Alonso under uncategorized

It may seem trivial but it has its tricky point. Usually, in procedural Javascript (this is, non object oriented programming), timers are set up passing the callback function on a string:

  1. function hello() {
  2.   alert("hello");
  3. }
  4. // Will execute hello() after 10 seconds
  5. setTimeout('hello()', 10000);

For this code to work, hello() has to be a global function (actually a function of the window object). Otherwise, when the timer times out, it won’t find it.

When writing object oriented code, one would like to call a function inside the object itself, not a global function. We can achieve this passing an anonymous function to the setTimeout function that calls our function:

  1. var MyClass = new Class({
  2.   initialize: function() {
  3.     setTimeout(function() { this.hello(); }, 10000); // This wont work
  4.   },
  5.   hello: function() {
  6.     alert("hello");
  7.   }
  8. });

The previous code wont work, since this inside the anonymous function points to the window object and not to our instance of MyClass. We solve this using the bind function provided by Mootools:

  1. var MyClass = new Class({
  2.   initialize: function() {
  3.     setTimeout(function() { this.hello(); }.bind(this), 10000);
  4.   },
  5.   hello: function() {
  6.     alert("hello");
  7.   }
  8. });

This code will work fine, but it still has a big problem. If we wanted to access any member or function of our instance inside the hello() function, it wouldn’t work. This is because when the timer times out, the context of our instance is lost. Inside the hello() function, this will point to the window object.

  1. var MyClass = new Class({
  2.   initialize: function() {
  3.     this.text = 'hello';
  4.     setTimeout(function() { this.hello(); }.bind(this), 10000);
  5.   },
  6.   hello: function() {
  7.     alert(this.text); // This wont work
  8.   }
  9. });

There are multiple ways to solve this issue but my favorite is to use the function call() of the function object. This function let’s you pass an object while calling your function that will become this inside it.

  1. var MyClass = new Class({
  2.   initialize: function() {
  3.     this.text = 'hello';
  4.     setTimeout(function() { this.hello.call(this); }.bind(this), 10000);
  5.   },
  6.   hello: function() {
  7.     alert(this.text);
  8.   }
  9. });

Now we can use this inside the hello() function and everything will work fine, no matter how many instances of MyClass we create.

  1. var MyClass = new Class({
  2.   initialize: function(text) {
  3.     this.text = text;
  4.     setTimeout(function() { this.hello.call(this); }.bind(this), 10000);
  5.   },
  6.   hello: function() {
  7.     alert(this.text);
  8.   }
  9. });
  10. new MyClass('hello');
  11. new MyClass('hi there!');
  12. new MyClass('wassup?');

Enjoy :)

2 responses so far