Module: Narou::Eventable

Included in:
Command::Setting, Command::Update, Downloader, PushServer, NovelConverter
Defined in:
lib/eventable.rb

Overview

Copyright 2013 whiteleaf. All rights reserved.

Defined Under Namespace

Modules: ClassMethods Classes: NonBlockError

Constant Summary collapse

EVENTS_CONTAINER =
{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
# File 'lib/eventable.rb', line 10

def self.included(base)
  super
  base.extend(ClassMethods)
  EVENTS_CONTAINER[base] = {}
end

Instance Method Details

#add_event_listener(event_name, once = false, &block) ⇒ Object Also known as: on

Raises:



34
35
36
37
38
39
# File 'lib/eventable.rb', line 34

def add_event_listener(event_name, once = false, &block)
  raise NonBlockError unless block_given?
  @__events_container ||= {}
  stack = @__events_container[event_name] ||= []
  stack.push([block, once])
end

#one(event_name, &block) ⇒ Object



69
70
71
# File 'lib/eventable.rb', line 69

def one(event_name, &block)
  add_event_listener(event_name, true, &block)
end

#remove_event_listener(event_name, &block) ⇒ Object Also known as: off



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

def remove_event_listener(event_name, &block)
  @__events_container ||= {}
  if block_given?
    events = @__events_container[event_name]
    if events
      events.reject! do |values|
        values[0] == block
      end
    end
  else
    @__events_container.delete(event_name)
  end
end

#trigger_event(event_name, *argv) ⇒ Object Also known as: trigger



55
56
57
58
59
60
61
62
63
# File 'lib/eventable.rb', line 55

def trigger_event(event_name, *argv)
  @__events_container ||= {}
  stack = @__events_container[event_name]
  return unless stack
  stack.reject! do |block, once|
    block.call(*argv)
    once
  end
end