-
Notifications
You must be signed in to change notification settings - Fork 0
Events
HH contains an event system roughly following the Observer design pattern. The implementation is contained in lib/dev/events.rb.
An event is composed of a Symbol (its name and identifier), and a number of parameters, which can be of any class.
To be able to emit events the HH::Observable module has to be mixed in, either by including it in a class or by extending an object.
When you want an event to happen call the emit method on the object, the first argument is the event symbol, while any additional paramaters will be the parameters of the event
obj.extend HH::Observable obj.emit :my_event, "test event", 123
An alternative way to pass parameters to an event is by using a Hash containing :parameter_symbol => value pairs.
emit :my_event, :par1 => "test event", :par2 => 123
To connect events call the on_event method on the Observable object, its parameters are the event symbol and the conditions for the event parameters.
A condition will match a parameter if condition === parameter evaluates to true. === is the same operator as is used to check equality within case statements. Note that the === operator is not symmetric.
on_event :my_event, /test/, Numeric do ... end # 1 on_event :my_event, /test/, String do ... end # 2 on_event :my_event, /test/ do ... end # 3 emit :my_event, "test event", 123 # will call 1 but not 2 and 3
The :any symbol can be used as a jolly that matches any parameter.
on_event :my_event, /test/, :any do ... end # 1 on_event :my_event, :any do ... end # 2 emit :my_event, "test event", 123 # will call 1 but not 2
If a Hash is used for the parameters, the second parameter of on_emit should also be a Hash. It will match if all values in the condition match their corresponding parameter.
on_event :my_event :par2 => Numeric do ... end # 1 on_event :my_event :any do ... end # 2 on_event :my_event :par3 => Numeric do ... end # 3 on_event :my_event String, Numeric do ... end # 4 emit :my_event :par1 => "test event, :par2 => 123 # will only call 1 and 2
on_event creates an HH::EventConnection event which will be returned by the method.
delete_event_connection takes an HH::EventConnection as parameter and removes it.
conn1 = on_event :evnt, String do ... end # 1 conn2 = on_event :evnt, String do ... end # 2 delete_event_connection conn1 emit :evnt, "my string" # will only call 2