lib/eventable/eventable.rb
# Allows an object to listen for an event and have a callback run when the event happens
Allows an object to listen for an event and have a callback run when the event happens
Allows an object to listen for an event and have a callback run when the event happens
def register_for_event(args)
    [:event, :listener, :callback].each do |parameter|
      raise ArgumentError, "Missing parameter :#{parameter}" unless args[parameter]
    end
    check_mutex
    @eventable_mutex.synchronize {
      event = args[:event]
      raise Errors::UnknownEvent unless events.include? event
      @callbacks ||= {}
      @callbacks[event] ||= {}
      listener    = args[:listener]
      listener_id = listener.object_id
      callback    = args[:callback]
      @callbacks[event][listener_id] ||= []
      @callbacks[event][listener_id] << callback
      ObjectSpace.define_finalizer(
        listener, 
        unregister_finalizer(event, listener_id, callback)
      )
    }
  end
def register_for_event ( args ) [ :event , :listener , :callback ] . each do | parameter | raise ArgumentError , "Missing parameter :#{parameter}" unless args [ parameter ] end check_mutex @eventable_mutex . synchronize { event = args [ :event ] raise Errors :: UnknownEvent unless events . include? event @callbacks ||= { } @callbacks [ event ] ||= { } listener = args [ :listener ] listener_id = listener . object_id callback = args [ :callback ] @callbacks [ event ] [ listener_id ] ||= [ ] @callbacks [ event ] [ listener_id ] << callback ObjectSpace . define_finalizer ( listener , unregister_finalizer ( event , listener_id , callback ) ) } end
Allows an object to listen for an event and have a callback run when the event happens
Allows an object to listen for an event and have a callback run when the event happens
# Make access to the callback array threadsafe # save the callback info without creating a reference to the object # will remove the object from the callback list if it is destroyed
args