Last active
August 27, 2021 23:05
-
-
Save icavalheiro/d58815b45d1dc707d53ba0ec7c36334c to your computer and use it in GitHub Desktop.
React Event Hub (useEvent)
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
import { useEffect } from 'react'; | |
class EventHub | |
{ | |
private listeners: {}; | |
constructor () | |
{ | |
this.listeners = {}; | |
} | |
public addListener ( type: string, listener: ( payload: any ) => {} ) | |
{ | |
if ( !this.listeners[ type ] ) | |
{ | |
this.listeners[ type ] = []; | |
} | |
this.listeners[ type ].push( listener ); | |
} | |
public removeListener ( type: string, listener: ( payload: any ) => {} ) | |
{ | |
if ( !this.listeners[ type ] ) | |
return; | |
this.listeners[ type ] = this.listeners[ type ].filter( x => x != listener ); | |
} | |
public dispatchEvent ( type: string, payload: any ) | |
{ | |
if ( !this.listeners[ type ] ) | |
return; | |
for ( let i = 0; i < this.listeners[ type ].length; i++ ) | |
{ | |
this.listeners[ type ][ i ](); | |
} | |
} | |
public useEvent ( type: string, listener: ( payload: any ) => {} ) | |
{ | |
useEffect( () => | |
{ | |
this.addListener( type, listener ); | |
return () => | |
{ | |
this.removeListener( type, listener ); | |
}; | |
} ); | |
} | |
} | |
const eventHub = new EventHub(); | |
export default eventHub; | |
export var useEvent = eventHub.useEvent.bind( eventHub ); | |
export var dispatchEvent = eventHub.dispatchEvent.bind( eventHub ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
CounterDisplay.js
CounterButton.js