Tag Archives: design pattern

Observer Pattern in JavaScript

Here is a simple, straight-forward observer implementation in JavaScript that you can use in any modern JavaScript environment. Please note that IE8 and below cannot use Array.prototype.filter and Array.prototype.forEach.

var Observable = {
  listeners: [ /* { event: String, fn: Function } */ ],
  _addListener: function(event, fn) {
    this.listeners.push({ event: event, fn: fn });
  },
  _removeListener: function(event) {
    this.listeners = this.listeners.filter(function(listenerObj) {
      return listenerObj.event !== event; 
    });
  },
  on: function(event, fn) {
    this._addListener(event, fn);  
  },
  off: function(event) {
    this._removeListener(event);  
  },
  listenTo: function(target, event, fn) {
    target._addListener(event, fn);
  },
  trigger: function(event) {
    this.listeners.filter(function(listenerObj) {
      return listenerObj.event === event; 
    }).forEach(function(listenerObj) {
      listenerObj.fn(listenerObj.event); 
    });
  },
};

You can set this object to a prototype of any of your classes:

// new class Person
var Person = function(name) {
  this.name = name;
};

// inherit from Observable
Person.prototype = Observable;

// define getName method
Object.defineProperty(Person.prototype, 'getName', {
  writable: false,
  value: function() {
     return this.name;  
  }
});

Any object that you instantiate from “Person” now is observable. This means you can easily do the following:

var jon    = new Person('Jon Snow');
var tyrion = new Person('Tyrion Lannister');

jon.listenTo(tyrion, 'greeting', function(event) {
  console.log('Received a ' + event + ' from ' + tyrion.getName());
});

jon.on('bye', function(event) {
  console.log('Received a ' + event + ' from ' + jon.getName());
});

tyrion.trigger('greeting'); // "Received a greeting from..."
jon.trigger('bye'); // "Received a bye from..."

jon.off('bye'); // unbinds all 'bye' listeners
jon.trigger('bye'); // does not fire anything

The syntax is very similar to Backbone, but of course without any dependencies. This code works best in a modern NodeJS environment where you do not need to support old JavaScript implementations. Bitbucket repository.

Simple Registry Pattern Implementation in JavaScript

Have you ever had to deal with something like this?

switch (input) {
    case '200':
        correspondingEvent = 'success';
        break;
    case '404':
        correspondingEvent = 'error';
        break;
    case '500':
        correspondingEvent = 'error';
        break;     
    // etc...
}

A huge switch statement that you cannot dynamically change. There is a design pattern called Registry Pattern for exactly this case. It is basically an object/array which maps different conditions.

Here is a JavaScript implementation of said pattern:

var registry = {
    '200': 'success',
    '404': 'error',
    '500': 'error',
    '403': 'error',
};

var input = '200', correspondingEvent;

if (input in registry) {
    correspondingEvent = registry[input];   
} else {
    // handle invalid input   
}

Adding or removing new cases is very easy:

registry['401'] = 'error';
delete registry['401'];

I would like to thank Christian Strotz for opening my eyes on this one, since I originally used an array instead of an object. (like in most other programming languages).