Sha256: 84cd6acd41365bbe197406f4d3d7dc2565fe7e5d00aeb22ad71444e012f84fd9

Contents?: true

Size: 1.24 KB

Versions: 7

Compression:

Stored size: 1.24 KB

Contents

module Safubot
  ##
  # A mixin granting simple event firing and handler binding.
  module Evented
	##
	# Binds an event handler, which is a Hash of the form:
	#
	# 	{ :evid => Symbol, :id => Symbol, :repeat => Boolean, :proc => Proc }
	#
	# See Evented#on and Evented#once for sugar.
	def bind(evid, handler)
	  @handlers ||= {}
	  @handlers[evid] ||= {}
	  handler[:evid] = evid
	  handler[:id] ||= @handlers[evid].length
	  @handlers[evid][handler[:id]] = handler
	end

	##
	# Unbinds the given handler.
	def unbind(handler)
	  @handlers[handler[:evid]].delete(handler[:id])
	end
	
	##
	# Binds a block to the specified event id.
	# Returns the bound handler.
	def on(evid, opts={}, &callback)
	  bind(evid, { :repeat => true, :proc => callback }.merge(opts))
	end

	##
	# Binds a block to the specified event id, to be executed only once.
	# Returns the bound handler.
	def once(evid, opts={}, &callback)
	  bind(evid, { :repeat => false, :proc => callback }.merge(opts))
	end

	##
	# Fires an evid event with the given arguments.
	def emit(evid, *args)
	  return unless @handlers && @handlers[evid]
	  @handlers[evid].each do |id, handler| 
		begin
		  handler[:proc].call(*args)
		ensure
		  @handlers[evid].delete(id) if !handler[:repeat]
		end
	  end
	end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
safubot-0.0.9 lib/safubot/evented.rb
safubot-0.0.8 lib/safubot/evented.rb
safubot-0.0.7 lib/safubot/evented.rb
safubot-0.0.6 lib/safubot/evented.rb
safubot-0.0.5 lib/safubot/evented.rb
safubot-0.0.4 lib/safubot/evented.rb
safubot-0.0.3 lib/safubot/evented.rb