Skip to content

Instantly share code, notes, and snippets.

@anasnakawa
Last active February 2, 2023 08:14
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save anasnakawa/9205494 to your computer and use it in GitHub Desktop.
Save anasnakawa/9205494 to your computer and use it in GitHub Desktop.
very tiny Pub/Sub implementation that utilizes native browser event methods. ( only browsers .. no IE8 )
/*! Js Pub/Sub
* http://anasnakawa.com/
* Copyright (c) Anas Nakawa
* inspired by Ben Alman's 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 = {} );
@anasnakawa
Copy link
Author

how to use it:

pubsub.subscribe( 'something', function( e ) {
  // data available as e.data 
});

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

@flexelektro
Copy link

wonderful ! thx

@skeep
Copy link

skeep commented Feb 17, 2015

very useful

@staxmanade
Copy link

staxmanade commented Jun 28, 2018

Hope this helps.

The handler.bind( context ) in both the add and remove event listener will cause issues as remove never actually works...

EX: the second publish you'd hope doesn't log anything because it was supposedly unsubscribed (but it actually wasn't...)

function handler( e ) {
  // data available as e.data 
  console.log('hello');
}

pubsub.subscribe( 'something', handler);

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

pubsub.unsubscribe( 'something', handler);

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

the fix: don't bind any context - let that be done by the person creating the handler function itself

/*! Js Pub/Sub
 * http://anasnakawa.com/
 * Copyright (c) Anas Nakawa 
 * inspired by Ben Alman's 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 ) {
    addEventListener( name, handler );
  };

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

})( this.pubsub = {} );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment