Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly, in Ruby there are no method signatures. The closest would be checking the function's arity. Duck typing requires thinking differently (slightly).</p> <p>The Observable module is a start, but if you have a requirement to have multiple events from a single class it might not be enough.</p> <p>This is a quick sketch. It supports methods and blocks. Modify as necessary to adapt for your code, threading approach, etc. For example, you could use method_missing to have the event name in the method name rather than having it as a parameter.</p> <pre><code>class EventBase def initialize @listeners = Hash.new end def listen_event(name, *func, &amp;p) if p (@listeners[name] ||= Array.new) &lt;&lt; p else (@listeners[name] ||= Array.new) &lt;&lt; func[0] end end def ignore_event(name, func) return if !@listeners.has_key?(name) @listeners[name].delete_if { |o| o == func } end def trigger_event(name, *args) return if !@listeners.has_key?(name) @listeners[name].each { |f| f.call(*args) } end end class MyClass &lt; EventBase def raise_event1(*args) trigger_event(:event1, *args) end def raise_event2(*args) trigger_event(:event2, *args) end end class TestListener def initialize(source) source.listen_event(:event1, method(:event1_arrival)) source.listen_event(:event2) do |*a| puts "event 2 arrival, args #{a}" end end def event1_arrival(*a) puts "Event 1 arrived, args #{a}" end end s = MyClass.new l = TestListener.new(s) s.raise_event1("here is event 1") s.raise_event2("here is event 2") </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload