Class: Three::EventDispatcher
- Inherits:
-
Object
- Object
- Three::EventDispatcher
show all
- Defined in:
- lib/three/core/event_dispatcher.rb
Defined Under Namespace
Classes: Event
Instance Method Summary
collapse
Constructor Details
Returns a new instance of EventDispatcher.
7
8
9
|
# File 'lib/three/core/event_dispatcher.rb', line 7
def initialize
@listeners = Hash.new { |hash, key| hash[key] = [] }
end
|
Instance Method Details
#add_event_listener(type, listener = nil, &block) ⇒ Object
Also known as:
on
11
12
13
14
15
16
17
18
|
# File 'lib/three/core/event_dispatcher.rb', line 11
def add_event_listener(type, listener = nil, &block)
callback = listener || block
raise ArgumentError, "listener or block is required" unless callback
listeners = @listeners[type.to_sym]
listeners << callback unless listeners.include?(callback)
self
end
|
#dispatch_event(event, data = nil) ⇒ Object
33
34
35
36
37
38
39
40
41
42
|
# File 'lib/three/core/event_dispatcher.rb', line 33
def dispatch_event(event, data = nil)
event = normalize_event(event, data)
listeners = @listeners[event.type.to_sym]
return self if listeners.empty?
event.target = self
listeners.dup.each { |listener| listener.call(event) }
event.target = nil
self
end
|
#has_event_listener?(type, listener) ⇒ Boolean
22
23
24
|
# File 'lib/three/core/event_dispatcher.rb', line 22
def has_event_listener?(type, listener)
@listeners[type.to_sym].include?(listener)
end
|
#remove_event_listener(type, listener) ⇒ Object
Also known as:
off
26
27
28
29
|
# File 'lib/three/core/event_dispatcher.rb', line 26
def remove_event_listener(type, listener)
@listeners[type.to_sym].delete(listener)
self
end
|