Sha256: 51ad9e614f4ea5baa9152f21c14fe01f3a535e2f508ebb024e01d3d5de411a96

Contents?: true

Size: 933 Bytes

Versions: 3

Compression:

Stored size: 933 Bytes

Contents

module BubbleWrap
  module Reactor
    # A simple mixin that adds events to your object.
    module Eventable

      # When `event` is triggered the block will execute
      # and be passed the arguments that are passed to
      # `trigger`.
      def on(event, method = nil, &blk)
        method_or_block = method ? method : blk
        __events__[event].push method_or_block
      end

      # When `event` is triggered, do not call the given
      # block any more
      def off(event, method = nil, &blk)
        method_or_block = method ? method : blk
        __events__[event].delete_if { |b| b == method_or_block }
        blk
      end

      # Trigger an event
      def trigger(event, *args)
        blks = __events__[event].clone
        blks.map do |blk|
          blk.call(*args)
        end
      end

      private

      def __events__
        @__events__ ||= Hash.new { |h,k| h[k] = [] }
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
bubble-wrap-1.7.0 motion/reactor/eventable.rb
bubble-wrap-1.6.0 motion/reactor/eventable.rb
bubble-wrap-1.6.0.rc1 motion/reactor/eventable.rb