module Tardvig::Events::Proxy
It allows to listens events of object using another object. It is useful when you do not have a direct access to object which you are want to listen on, for example, when you have access only to GameIO
from a display.
To proxy an event from an object, you need to add this object to {#tracked_list} through {#spy_on} and then you can bind a listener on it through proxy (see {#on} for syntax).
If you want proxy to forward event to itself even if you have not bound a listener, you can trigger the `:wait_for_event` event on the proxy. You should pass the name of the event you are waiting for as an argument.
Public Instance Methods
# File lib/tardvig/events/proxy.rb, line 28 def happen(event, data = nil) track_event data if event == :wait_for_event super event, data end
It works like the original Events#on
, but it also can bind listeners to objects from the {tracked_list}.
To do it, you need to set event name using next syntax: `tracked_obj_name:event_name`.
`tracked_obj_name` is {DataIdentifier} of an object (from {tracked_list}) which you want to bind listener to.
`event_name` is the event of this object. The `listener` will be binded to this event. Important! When you will trigger this event, its name must be a Symbol.
See spec if you have not understood.
# File lib/tardvig/events/proxy.rb, line 48 def on(event, &listener) track_event event super event, &listener end
Adds objects to tracked list so you can bind proxy listeners to them @param [Hash] `name: object` pairs.
# File lib/tardvig/events/proxy.rb, line 18 def spy_on(objects) tracked_list.merge! objects end
@return [Hash] objects (with their names as keys) which you can bind
proxy listeners to.
# File lib/tardvig/events/proxy.rb, line 24 def tracked_list @tracked_list ||= ({}.extend DataIdentifier) end
Private Instance Methods
# File lib/tardvig/events/proxy.rb, line 65 def bind_proxy_listener(target, full_event_name, event_name) target.on event_name.to_sym do |data| happen full_event_name, data end end
# File lib/tardvig/events/proxy.rb, line 55 def track_event(event) event_id_parts = event.to_s.split ':' if event_id_parts.size == 2 event_target = tracked_list.get_this event_id_parts[0] if event_target bind_proxy_listener event_target, event, event_id_parts[1] end end end