Sha256: 4388f907e77b14a2656311b18c371063f9a6540b67f3e9a35b5c24be904f9fac
Contents?: true
Size: 1.27 KB
Versions: 3
Compression:
Stored size: 1.27 KB
Contents
module EventEmitter def self.included(klass) klass.extend ClassMethods klass.__send__ :include, InstanceMethods end def self.apply(object) object.extend InstanceMethods end module ClassMethods end module InstanceMethods def __events @__events ||= [] end def add_listener(type, params={}, &block) raise ArgumentError, 'listener block not given' unless block_given? id = __events.empty? ? 0 : __events.last[:id]+1 __events << { :type => type.to_sym, :listener => block, :params => params, :id => id } id end alias :on :add_listener def remove_listener(id_or_type) if id_or_type.class == Fixnum __events.delete_if do |e| e[:id] == id_or_type end elsif [String, Symbol].include? id_or_type.class __events.delete_if do |e| e[:type] == id_or_type.to_sym end end end def emit(type, *data) __events.each do |e| if e[:type] == type.to_sym listener = e[:listener] remove_listener e[:id] if e[:params][:once] instance_exec(*data, &listener) end end end def once(type, &block) add_listener type, {:once => true}, &block end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
event_emitter-0.2.2 | lib/event_emitter/emitter.rb |
event_emitter-0.2.1 | lib/event_emitter/emitter.rb |
event_emitter-0.2.0 | lib/event_emitter/emitter.rb |