2015-07-23 19:09:19 +02:00
|
|
|
# A simple event registering/triggering module to mix into classes.
|
|
|
|
# Events are stored in the `@events` ivar.
|
|
|
|
module Eventable
|
|
|
|
|
|
|
|
# Register a handler for the given event name.
|
2015-07-24 09:01:01 +02:00
|
|
|
# The event name is the method name called on the handler object
|
2015-07-23 19:09:19 +02:00
|
|
|
#
|
2015-07-24 09:01:01 +02:00
|
|
|
# obj.on(:foo , some_object_that_implements foo( whateverargs)
|
2015-07-23 19:09:19 +02:00
|
|
|
#
|
|
|
|
# @param [String, Symbol] name event name
|
2015-07-24 09:01:01 +02:00
|
|
|
# @param [Object] object handling the event, ie implement the function name
|
2015-07-23 19:09:19 +02:00
|
|
|
# @return handler
|
2015-07-24 09:01:01 +02:00
|
|
|
def register_event(name, handler)
|
2015-07-23 19:09:19 +02:00
|
|
|
event_table[name] << handler
|
|
|
|
handler
|
|
|
|
end
|
|
|
|
|
2015-07-24 09:01:01 +02:00
|
|
|
def unregister_event(name, handler)
|
2015-07-23 19:09:19 +02:00
|
|
|
event_table[name].delete handler
|
|
|
|
end
|
|
|
|
|
|
|
|
def event_table
|
|
|
|
return @event_table if @event_table
|
|
|
|
@event_table = Hash.new { |hash, key| hash[key] = [] }
|
|
|
|
end
|
|
|
|
|
|
|
|
# Trigger the given event name and passes all args to each handler
|
|
|
|
# for this event.
|
|
|
|
#
|
|
|
|
# obj.trigger(:foo)
|
|
|
|
# obj.trigger(:foo, 1, 2, 3)
|
|
|
|
#
|
|
|
|
# @param [String, Symbol] name event name to trigger
|
|
|
|
def trigger(name, *args)
|
2015-07-24 09:01:01 +02:00
|
|
|
event_table[name].each { |handler| handler.send( name.to_sym , *args) }
|
2015-07-23 19:09:19 +02:00
|
|
|
end
|
|
|
|
end
|