aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/event_emitter.rb
blob: 7bc96951e87132de90b57185122d62ccb7b8be29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# -*- 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[name] ||= []) << blk
    end

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

    private
    def callbacks
      @callbacks ||= {}
    end
  end
end