Skip to content

Instantly share code, notes, and snippets.

@gesslar
Last active April 10, 2021 03:24
Show Gist options
  • Save gesslar/f53ddaa3b20b17a0dc27177e367ffd99 to your computer and use it in GitHub Desktop.
Save gesslar/f53ddaa3b20b17a0dc27177e367ffd99 to your computer and use it in GitHub Desktop.
// /std/events.c
// Event emitter inheritible
//
// Created: 2021/04/09: Gesslar
// Last Change: 2021/04/09: Gesslar
//
// 2021/04/09: Gesslar - Created
private static mapping event_listeners = ([ ]) ;
// Makes sure the event name is a proper string
int validate_event_name( string event_name )
{
return !nullp( event_name ) && stringp( event_name ) && strlen( event_name ) > 0 ;
}
// Add a new event to the event_listeners mapping
nomask int add_event( string event_name )
{
if( !validate_event_name( event_name ) ) return 0 ;
if( !nullp( event_listeners[ event_name ] ) ) return 0 ;
event_listeners[ event_name ] = ({ }) ;
return 1 ;
}
// Remove an event from the event_listeners mapping
nomask int remove_event( string event_name )
{
if( !validate_event_name( event_name ) ) return 0 ;
if( nullp( event_listeners[ event_name ] ) ) return 0 ;
map_delete( event_listeners, event_name ) ;
return 1 ;
}
// Add a new listener to an existing, exposed event
nomask varargs int add_listener( string event_name, object listener )
{
object *listeners ;
if( !validate_event_name( event_name ) ) return 0 ;
if( nullp( event_listeners[ event_name ] ) ) return 0 ;
if( nullp( listener ) ) listener = previous_object() ;
else if( !objectp( listener ) ) return 0 ;
listeners = event_listeners[ event_name ] - ({ 0 }) ;
if( member_array( listener, listeners ) > -1 ) return 0 ;
listeners += ({ listener }) ;
event_listeners[ event_name ] = listeners ;
return 1 ;
}
// Remove a listener from an existing, exposed event
nomask varargs int remove_listener( string event_name, object listener )
{
object *listeners ;
if( !validate_event_name( event_name ) ) return 0 ;
if( nullp( event_listeners[ event_name ] ) ) return 0 ;
if( nullp( listener ) ) listener = previous_object() ;
else if( !objectp( listener ) ) return 0 ;
listeners = event_listeners[ event_name ] - ({ 0 }) ;
if( member_array( listener, listeners ) == -1 ) return 0 ;
listeners -= ({ listener }) ;
event_listeners[ event_name ] = listeners ;
return 1 ;
}
// Emit to all listeners the event name
void event_emit( string event_name, mixed *args... )
{
object *listeners ;
if( !validate_event_name( event_name ) ) return ;
if( !pointerp( event_listeners[ event_name ] ) ) return ;
if( nullp( event_listeners[ event_name ] ) ) return ;
listeners = event_listeners[ event_name ] - ({ 0 }) ;
event_listeners[ event_name ] = listeners ;
catch ( call_other( listeners, event_name, this_object(), args... ) ) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment