Sha256: b975806ebda83ffde070ffa6011e66075ad273c086b1d808d5e4225ae27bb4cd

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

module Vedeu
  class Events

    # @param block [Proc]
    # @return [Events]
    def initialize(&block)
      @handlers = Hash.new { |hash, key| hash[key] = { events: [] } }

      instance_eval(&block) if block_given?
    end

    # @param object []
    # @param block [Proc]
    # @return []
    def add(object, &block)
      @self_before_instance_eval = eval('self', block.binding)

      instance_eval(&block)
    end

    # @see Vedeu::API#event
    def event(name, opts = {}, &block)
      handlers[name][:events] << Event.new(block, opts)
      handlers[name]
    end

    # Unregisters the event by name, effectively deleting the associated events
    # bound with it also.
    #
    # @param name [Symbol]
    # @return []
    def unevent(name)
      handlers.delete_if { |k, v| k == name }
    end

    # Returns a collection of the names of all the registered events.
    #
    # @return [Array]
    def registered
      handlers.keys
    end

    # @see Vedeu::API#trigger
    def trigger(name, *args)
      handlers[name][:events].each { |event| event.trigger(*args) }
    end

    # Remove all registered events. Used for testing purposes.
    #
    # @return []
    def reset
      @handlers = Hash.new { |hash, key| hash[key] = { events: [] } }
    end

    private

    attr_reader :handlers

    def method_missing(method, *args, &block)
      @self_before_instance_eval.send(method, *args, &block)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vedeu-0.1.17 lib/vedeu/support/events.rb