Class: Unobservable::Event
- Inherits:
-
Object
- Object
- Unobservable::Event
- Defined in:
- lib/unobservable.rb
Overview
Minimalistic Event implementation
Instance Attribute Summary collapse
-
#handlers ⇒ Object
readonly
Returns the value of attribute handlers.
Instance Method Summary collapse
-
#call(*args, &block) ⇒ Object
Pass the specific arguments / block to all of the event handlers.
-
#handler_for(*args, &block) ⇒ Object
There are 3 ways for end-users to provide an event handler:.
-
#initialize ⇒ Event
constructor
A new instance of Event.
-
#register(*args, &block) ⇒ Object
Registers the given event handler so that it will be invoked when the event is raised.
-
#unregister(*args, &block) ⇒ Object
Removes a single instance of the specified event handler from the list of event handlers.
Constructor Details
#initialize ⇒ Event
Returns a new instance of Event.
155 156 157 |
# File 'lib/unobservable.rb', line 155 def initialize @handlers = [] end |
Instance Attribute Details
#handlers ⇒ Object (readonly)
Returns the value of attribute handlers.
153 154 155 |
# File 'lib/unobservable.rb', line 153 def handlers @handlers end |
Instance Method Details
#call(*args, &block) ⇒ Object
Pass the specific arguments / block to all of the event handlers. Return true if there was at least 1 event handler; return false otherwise.
205 206 207 208 209 210 211 212 213 214 215 216 |
# File 'lib/unobservable.rb', line 205 def call(*args, &block) if @handlers.empty? return false else # TODO: Add some form of error-handling @handlers.each do |h| h.call(*args, &block) end return true end end |
#handler_for(*args, &block) ⇒ Object
There are 3 ways for end-users to provide an event handler:
-
They can pass an object that has a #call method
-
They can provide an object and the name of a method to invoke
-
They can pass in a block
164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/unobservable.rb', line 164 def handler_for(*args, &block) if block return block elsif args.size == 1 return args[0] elsif args.size == 2 return args[0].method(args[1]) end raise ArgumentError, "Unable to create an event handler using the given arguments" end |
#register(*args, &block) ⇒ Object
Registers the given event handler so that it will be invoked when the event is raised.
178 179 180 181 182 |
# File 'lib/unobservable.rb', line 178 def register(*args, &block) h = handler_for(*args, &block) @handlers << h return h end |
#unregister(*args, &block) ⇒ Object
Removes a single instance of the specified event handler from the list of event handlers. Therefore, if you’ve registered the same event handler 3 times, then you will need to unregister it 3 times as well.
189 190 191 192 193 194 195 196 197 198 |
# File 'lib/unobservable.rb', line 189 def unregister(*args, &block) h = handler_for(*args, &block) index = @handlers.index(h) if index @handlers.slice!(index) return h else return nil end end |