SleepyCod
by SleepyCod

Painless publish/subscribe system with swell’s custom events

Posted in Javascript, Swell

Let me start with wikipedia’s own publish/subscribe pattern definition : Publish/subscribe (or pub/sub) is an asynchronous messaging paradigm where senders (publishers) of messages are not programmed to send their messages to specific receivers (subscribers). This decoupling of publishers and subscribers can allow for greater scalability… We absolutely wanted to have this pattern implemented into Swell as we are fervent supporters of the SoC. The goal was to be able to hook the Custom event model to potentially any class as well as using custom events outside of a class context.

Custom event model

By inheriting the CustomEventModel class built-into swell, the children class is augmented with new methods and collections brought from the model. Example :

    Swell.Core.Class({
        name        : 'Hashtable',
        namespace   : 'Swell.Core',
        inherits    : [Swell.Core.Enumerable, Swell.Core.CustomEventModel],
        ...

Swell.Core.Hashtable class now have those methods :

  • createEvent (creates a custom event that is bound to the class ex : onHashUpdated)
  • fireEvent (fires desired event and will notice all the subscribers aka execute callback functions)
  • subscribe (subscribe to a custom event of the class from/outside the class)
  • unsubscribe
  • getEvents

In the hashtable code, we use custom events to update a static property containing the length.

var _initEvents = function() {
    /**
      * Initialization of the event
      * @event onChange fires when an item is added/updated in the hashtable
    */
    this.createEvent('onHashUpdated');
    this.subscribe('onHashUpdated', _updateLength); //_updateLength is a private function of the class
}
...
/**
 * Now triggering the event
*/
set : function(key, value) {
    if(arguments.length === 1) {
        _hash[Swell.uniqueId()] = key;
    } else {
        _hash[key] = value;
    }
    this.fireEvent('onHashUpdated', this);
    return this;
},
...

Standalone custom events

This is the simplest way of using the custom event system.
In the example below we have created a basic object called button that makes use of custom events.

var button = function() {
    var value = 1;
 
    this.setValue = function(val) {
        value = val;
        this.onValueChange.fire();
    };
 
    this.onValueChange = new Swell.Core.CustomEvent('onValueChange');
}
 
var handler = function() {
    alert('button value has changed');
}
 
var btn = new button();
btn.onValueChange.subscribe(handler);
btn.setValue('toto');

And the firebug DOM :

Firebug DOM

Firebug DOM

Tags: , , ,

One Response to “Painless publish/subscribe system with swell’s custom events”

  1. 1
    Cornelius Says:

    To follow, without halt, one aim: There’s the secret of success.

Leave a Reply