Class: Unobservable::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/unobservable.rb

Overview

Minimalistic Event implementation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEvent

Returns a new instance of Event.



190
191
192
# File 'lib/unobservable.rb', line 190

def initialize
  @handlers = []
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.



188
189
190
# File 'lib/unobservable.rb', line 188

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.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/unobservable.rb', line 229

def call(*args, &block)
  if @handlers.empty?
    return false
  else
    # TODO: Add some form of error-handling
    @handlers.each do |h|
      begin
        h.call(*args, &block)
      rescue Exception
        # TODO: Should probably log when this happens
      end
    end

    return true
  end
end

#register(*args, &block) ⇒ Object Also known as: add

Registers the given event handler so that it will be invoked when the event is raised.



198
199
200
201
202
# File 'lib/unobservable.rb', line 198

def register(*args, &block)
  h = Unobservable.handler_for(*args, &block)
  @handlers << h
  return h
end

#unregister(*args, &block) ⇒ Object Also known as: delete

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.



211
212
213
214
215
216
217
218
219
220
# File 'lib/unobservable.rb', line 211

def unregister(*args, &block)
  h = Unobservable.handler_for(*args, &block)
  index = @handlers.index(h)
  if index
    @handlers.slice!(index)
    return h
  else
    return nil
  end
end