library-ts/browser/events/EventSlot.ts

59 lines
935 B
TypeScript
Raw Normal View History

2025-03-23 07:31:36 +00:00
export type EventSlotCallback<T> = ( eventData:T ) => void;
export class EventSlot<T>
{
private _listeners:EventSlotCallback<T>[] = [];
addListener( callback:EventSlotCallback<T> )
{
this._listeners.push( callback );
}
once( callback:EventSlotCallback<T> )
{
let onceCallback = ( t:T ) =>
{
try
{
callback( t );
}
catch( e )
{
console.error( "Error on callback", e );
}
this.removeListener( onceCallback );
};
this.addListener( onceCallback );
}
removeListener( callback:EventSlotCallback<T> )
{
let index = this._listeners.indexOf( callback );
if ( index === -1 )
{
return;
}
this._listeners.splice( index, 1 );
}
removeAll()
{
this._listeners = [];
}
dispatch( eventData:T )
{
for ( let listener of this._listeners )
{
listener( eventData );
}
}
}