Module: Publisher::InstanceMethods

Defined in:
lib/publisher.rb

Overview

Container for the instance methods that will be mixed-in to extenders of Publisher. These methods get mixed in when you use the ‘has_events’ call.

Instance Method Summary collapse

Instance Method Details

#subscribe(event, target = nil, callback = nil, &block) ⇒ Object Also known as: when, on

Sign up a code block to be executed when an event is fired. It’s important to know the signature of the event, as your proc needs to accept incoming parameters accordingly.



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/publisher.rb', line 43

def subscribe(event, target=nil, callback=nil, &block)
  ensure_valid event
	@subscriptions ||= {}
	listeners = @subscriptions[event]
	listeners ||= []
    if target && callback
      listeners << [target, callback]
    else
      listeners << block
    end
	@subscriptions[event] = listeners
end

#unsubscribe(event, listener) ⇒ Object

Unsubscribe for an event. ‘listener’ is a reference to the object who enacted the subscription… often, this is ‘self’. If this object has subsribed more than once for the given event (unusual), all of the subscriptions will be removed.



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/publisher.rb', line 61

def unsubscribe(event, listener)
ensure_valid event
  if @subscriptions && @subscriptions[event]
    @subscriptions[event].delete_if do |block_or_target|
      if block_or_target.is_a? Proc
        eval('self',block_or_target.binding).equal?(listener)
      else
        block_or_target[0] == listener
      end
    end
  end
end