Last Updated: February 25, 2016
·
2.563K
· anasnakawa

very tiny PubSub using native browser methods

while I was hacking around my developer tools, I was wondering if I could write a PubSub implementation utilizing browser native Event system rather than writing my own one..

/*! tiny Js Pub/Sub
 * http://anasnakawa.com/
 * Copyright (c) Anas Nakawa 
 * inspired by Ben Alman's tiny one <https://gist.github.com/cowboy/661855>
 * MIT License  
 */

(function( p ) {

  var e = p.e = {};

  p.publish = function( name, data ) {
    ( e[ name ] = e[ name ] || new Event( name ) ).data = data;
    dispatchEvent( e[ name ] );
  };

  p.subscribe = function( name, handler, context ) {
    addEventListener( name, handler.bind( context ) );
  };

  p.unsubscribe = function( name, handler, context ) {
    removeEventListener( name, handler.bind( context ) );
  };

})( this.pubsub = {} );

Usage

// main usage
pubsub.subscribe( 'foo', function( e ) {
    e.data;
});

pubsub.publish( 'foo', { some: 'data' });

// unsubscribing
var handler = function( e ) {
    e.data;
}

pubsub.subscribe( 'bar', handler );
pubsub.unsubscribe( 'bar', handler );
  • works only on browser environments ( IE9+, Chrome, FF, ..etc )
  • not supported on Node Js environment
  • you can always refer to the updated gist overhere