Class: Inferno::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/inferno.rb

Instance Method Summary collapse

Constructor Details

#initializeEvent

Returns a new instance of Event.



7
8
9
10
# File 'lib/inferno.rb', line 7

def initialize
  @events  = {}
  @fibers  = []
end

Instance Method Details

#count(event) ⇒ Object



39
40
41
# File 'lib/inferno.rb', line 39

def count(event)
  @events[event] ? @events[event].size : 0
end

#eventsObject



16
17
18
# File 'lib/inferno.rb', line 16

def events
  @events.keys
end

#fibersObject



12
13
14
# File 'lib/inferno.rb', line 12

def fibers
  @fibers
end

#off(event, context = nil) ⇒ Object

Remove a previously-bound callback function from an object. If no context is specified, all of the versions of the callback with different contexts will be removed. If no event is specified, callbacks for all events will be removed.

Parameters:

  • [event (String)

    name]

  • [on (Object)

    what object run callback]



48
49
50
51
52
53
54
55
56
57
# File 'lib/inferno.rb', line 48

def off(event,context=nil)
  if @events[event]
    if context
      @events[event].delete(context) 
    else
      @events[event].clear
    end
    @events.delete(event) if @events[event].empty?
  end
end

#on(event, context, &callback) ⇒ Object

Bind a callback function to an object. The callback will be invoked whenever the event is fired.

Parameters:

  • [event (String)

    name]

  • [on (Object)

    what object run callback]

  • [callback (Proc)

    with proc]



34
35
36
37
# File 'lib/inferno.rb', line 34

def on(event, context, &callback)
  @events[event] ||= {}
  @events[event][context] = callback
end

#once(event, context, &callback) ⇒ Object

Just like on, but causes the bound callback to only fire once before being removed. Handy for saying “the next time that X happens, do this”.

Parameters:

  • [event (String)

    name]

  • [on (Object)

    what object run callback]

  • [callback] (Proc)


25
26
27
28
# File 'lib/inferno.rb', line 25

def once(event, context, &callback)
  on(event, context, &callback)
  on(event, self) { off(event) }
end

#trigger(event, payload = {}) ⇒ Object

Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

Parameters:

  • [event (String)

    name]

  • [payload (Hash)

    to send]



62
63
64
65
# File 'lib/inferno.rb', line 62

def trigger(event, payload={})
  broadcast(false, "triggered.event", { event: event, payload: payload })
  broadcast(true,  event, payload)
end