Module: Dilation::Utils::Events

Included in:
Core
Defined in:
lib/dilation/utils/events.rb

Overview

TODO:

fix return types

Defines an event handler system loosely based off of the DOM addEventListener pattern

Examples:

class Foo
  include Dilation::Utils::Events
  event :bar, :baz
  def baz
    bar
    __baz
  end
end
f = Foo.new
f.listen_for :bar, { puts 'bar' }
f.listen_for :baz, { puts 'baz' }
f.baz #=> prints bar then baz

Author:

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#clear(name) ⇒ Object

Clears all handlers for the event

Parameters:

  • name (String, Symbol, #to_sym)

    the event to clear



68
69
70
# File 'lib/dilation/utils/events.rb', line 68

def clear(name)
  handlers[name.to_sym] = []
end

#clear_allObject

Clear all tracked handlers



73
74
75
# File 'lib/dilation/utils/events.rb', line 73

def clear_all
  self.handlers = Hash.new { |h, k| h[k] = [] }
end

#dont_listen_for(name, handler) ⇒ Object

Removes a callable for the given event

Parameters:

  • name (String, Symbol, #to_sym)

    the event to remove from

  • handler (#call)

    the handler to remove



61
62
63
# File 'lib/dilation/utils/events.rb', line 61

def dont_listen_for(name, handler)
  handlers[name.to_sym].delete(handler)
end

#fire(name) ⇒ Object

Triggers the given event

Parameters:

  • name (String, Symbol, #to_sym)

    event to trigger



80
81
82
# File 'lib/dilation/utils/events.rb', line 80

def fire(name)
  handlers[name.to_sym].each(&:call)
end

#listen_for(name, handler) ⇒ Object #listen_for(name, &blk) ⇒ Object

Registers a block or callable for the given event

Overloads:

  • #listen_for(name, handler) ⇒ Object

    registers the handler for the event

    Parameters:

    • name (String, Symbol, #to_sym)

      the event to listen for

    • handler (#call)

      the handler to trigger for this event

  • #listen_for(name, &blk) ⇒ Object

    registers the block for the event

    Parameters:

    • name (String, Symbol, #to_sym)

      the event to listen for

    • blk

      the block to trigger for this event

Raises:

  • ArgumentError if handler or blk is not present



51
52
53
54
55
# File 'lib/dilation/utils/events.rb', line 51

def listen_for(name, handler = nil, &blk)
  to_add = handler || blk
  raise ArgumentError.new "handler or block required" unless to_add
  handlers[name.to_sym] << to_add
end