aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/event_emitter.rb
blob: e0684ddffc3d902276cdeb223b9a9c1a9391fee9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*- frozen-string-literal: true -*-
module Plum
  module EventEmitter
    # Registers an event handler to specified event. An event can have multiple handlers.
    # @param name [Symbol] The name of event.
    # @yield Gives event-specific parameters.
    def on(name, &blk)
      @callbacks ||= {}
      (@callbacks[name] ||= []) << blk
    end

    # Invokes an event and call handlers with args.
    # @param name [Symbol] The identifier of event.
    def callback(name, *args)
      @callbacks&.[](name)&.each { |cb| cb.call(*args) }
    end
  end
end