Module: Tardvig::Events

Included in:
GameIO, HashContainer
Defined in:
lib/tardvig/events.rb,
lib/tardvig/events/proxy.rb

Overview

The mixin gives ability to have events

Defined Under Namespace

Modules: Proxy

Instance Method Summary collapse

Instance Method Details

#happen(event, data = nil) ⇒ Object Also known as: trigger

Executes all the listeners which are bound to the given event name

Parameters:

  • data (Object) (defaults to: nil)

    the object will be passed as an argument to the listeners



37
38
39
40
41
# File 'lib/tardvig/events.rb', line 37

def happen(event, data = nil)
  listeners(event).clone.each do |listener|
    listener.call(data)
  end
end

#listeners(event) ⇒ Array

Returns array with all the listeners which are bound to the given event name.

Returns:

  • (Array)

    array with all the listeners which are bound to the given event name



47
48
49
50
# File 'lib/tardvig/events.rb', line 47

def listeners(event)
  @listeners ||= {}
  @listeners[event] ||= []
end

#on(event, &listener) ⇒ Object

Binds given listener (handler/callback) to given event name

Parameters:

  • event (Object)

    any custom identificator. Your listener will be executed only when you trigger event with this identificator.

  • listener (#call)

    this object will be executed (through the #call method) when you trigger the given event.



10
11
12
# File 'lib/tardvig/events.rb', line 10

def on(event, &listener)
  listeners(event) << listener
end

#on_first(event, &listener) ⇒ Object

Does the same as #on, but the listener will be executed only once, then it will be deleted.

Parameters:

  • event (Object)

    any custom identificator. Your listener will be executed only when you trigger event with this identificator.

  • listener (#call)

    this object will be executed (through the #call method) when you trigger the given event.



17
18
19
20
21
22
23
# File 'lib/tardvig/events.rb', line 17

def on_first(event, &listener)
  throwaway_callback = proc do |*args|
    remove_listener event, throwaway_callback
    listener.call(*args)
  end
  listeners(event) << throwaway_callback
end

#remove_listener(event, listener = nil) ⇒ Object

Unbinds given listener from the given event name



26
27
28
29
30
31
32
# File 'lib/tardvig/events.rb', line 26

def remove_listener(event, listener = nil)
  if listener.nil?
    listeners(event).clear
  else
    listeners(event).delete listener
  end
end