Sha256: 79325218132ec853fa3db8bfda8e08dd70d2a89016b9a98ae1df8051ee8f129c

Contents?: true

Size: 1.07 KB

Versions: 2

Compression:

Stored size: 1.07 KB

Contents

module WebSocket
  class Driver

    module EventEmitter
      def initialize
        @listeners = Hash.new { |h,k| h[k] = [] }
      end

      def add_listener(event, callable = nil, &block)
        listener = callable || block
        @listeners[event.to_s] << listener
        listener
      end

      def on(event, callable = nil, &block)
        add_listener(event, callable, &block)
      end

      def remove_listener(event, callable = nil, &block)
        listener = callable || block
        @listeners[event.to_s].delete(listener)
        listener
      end

      def remove_all_listeners(event = nil)
        if event
          @listeners.delete(event.to_s)
        else
          @listeners.clear
        end
      end

      def emit(event, *args)
        @listeners[event.to_s].dup.each do |listener|
          listener.call(*args)
        end
      end

      def listener_count(event)
        return 0 unless @listeners.has_key?(event.to_s)
        @listeners[event.to_s].size
      end

      def listeners(event)
        @listeners[event.to_s]
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
websocket-driver-0.6.0-java lib/websocket/driver/event_emitter.rb
websocket-driver-0.6.0 lib/websocket/driver/event_emitter.rb