Last active
February 2, 2023 08:14
-
-
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 )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! 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 = {} ); |
wonderful ! thx
very useful
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
how to use it: