@jkempema/messaging
v1.0.7
Published
messaging
Downloads
36
Readme
messaging
Library to provide publish and subscribe messaging.
Usage
Publish / Subscribe / Unsubscribe
import Dispatcher from 'messaging';
// Create Dispatcher
const dispatcher = new Dispatcher();
// Subscribe ( anonymous function )
const unsubscribe = dispatcher.subscribe( 'test', ( message ) => {
console.log( message );
} );
// Subscribe ( named function )
const handleMessage = ( message ) => {
console.log( message );
};
dispatcher.subscribe( 'test', handleMessage );
// Publish Message
dispatcher.publish( 'test', { text: 'some message' } );
// Unsubscribe ( anonymous function )
unsubscribe();
// Unsubscribe ( named function )
dispatcher.unsubscribe( 'test', handleMessage );
Defer Message Handling
import Dispatcher from 'messaging';
const dispatcher = new Dispatcher();
const unsubscribe = dispatcher.subscribe( 'test', ( message, defer ) => {
defer( ( done ) => {
// Do something that may take some time...
done();
} );
} );
// Publish Message
dispatcher.publish( 'test', { text: 'some message' } ).then( () => {
// This will not execute untill all subscribers have processed the message.
} );;
// Unsubscribe
unsubscribe();
Global Dispatcher
The Dispatcher class has a global property to provide a means where messaging can accessed across libraries.
import Dispatcher from 'messaging'
const globalDispatcher = Dispatcher.global;