1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
# frozen_string_literal: true
module HTTP2
# Basic event emitter implementation with support for persistent and
# one-time event callbacks.
#
module Emitter
# Subscribe to all future events for specified type.
#
# @param event [Symbol]
# @param block [Proc] callback function
def on(event, &block)
raise ArgumentError, "must provide callback" unless block
@listeners[event] << block
end
# Subscribe to next event (at most once) for specified type.
#
# @param event [Symbol]
# @param block [Proc] callback function
def once(event, &block)
on(event) do |*args, &callback|
block.call(*args, &callback)
:delete
end
end
# Emit event with provided arguments.
#
# @param event [Symbol]
# @param args [Array] arguments to be passed to the callbacks
# @param block [Proc] callback function
def emit(event, *args, &block)
@listeners[event].delete_if do |cb|
:delete == cb.call(*args, &block) # rubocop:disable Style/YodaCondition
end
end
end
end
|