Module: Puppeteer::EventCallbackable
- Included in:
- Browser, BrowserContext, CDPSession, Connection, FrameManager, NetworkManager, Page
- Defined in:
- lib/puppeteer/event_callbackable.rb
Defined Under Namespace
Classes: EventListeners
Instance Method Summary collapse
- #add_event_listener(event_name, &block) ⇒ Object
- #emit_event(event_name, *args, **kwargs) ⇒ Object
- #on_event(event_name, &block) ⇒ Object
- #remove_event_listener(*id_args) ⇒ Object
Instance Method Details
#add_event_listener(event_name, &block) ⇒ Object
29 30 31 32 |
# File 'lib/puppeteer/event_callbackable.rb', line 29 def add_event_listener(event_name, &block) @event_listeners ||= {} (@event_listeners[event_name] ||= EventListeners.new).add(&block) end |
#emit_event(event_name, *args, **kwargs) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/puppeteer/event_callbackable.rb', line 47 def emit_event(event_name, *args, **kwargs) @event_callbackable_handlers ||= {} @event_listeners ||= {} if kwargs.empty? # In Ruby's specification (version < 2.7), # `method(:x).call(*args, **kwargs)` is equivalent to `x(*args, {})` # It often causes unexpected ArgumentError. # # ---------------- # def greet # puts 'Hello!' # end # # def call_me(*args, **kwargs) # greet(*args, **kwargs) # => 'Hello!' # # method(:greet).call(*args, **kwargs) # => `greet': wrong number of arguments (given 1, expected 0) (ArgumentError) # end # # call_me # ---------------- # # This behavior is really annoying, and should be avoided, because we often want to set event handler as below: # # `on_event 'Some.Event.awesome', &method(:handle_awesome_event)` # # So Let's avoid it by checking kwargs. @event_callbackable_handlers[event_name]&.call(*args) @event_listeners[event_name]&.each do |proc| proc.call(*args) end else @event_callbackable_handlers[event_name]&.call(*args, **kwargs) @event_listeners[event_name]&.each do |proc| proc.call(*args, **kwargs) end end event_name end |
#on_event(event_name, &block) ⇒ Object
42 43 44 45 |
# File 'lib/puppeteer/event_callbackable.rb', line 42 def on_event(event_name, &block) @event_callbackable_handlers ||= {} @event_callbackable_handlers[event_name] = block end |
#remove_event_listener(*id_args) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/puppeteer/event_callbackable.rb', line 34 def remove_event_listener(*id_args) (@event_listeners ||= {}).each do |event_name, listeners| id_args.each do |id| listeners.delete(id) end end end |