Module: Observable

Included in:
Qt::Base
Defined in:
lib/rui/observer_utils.rb

Overview

Extensions to the standard Observable module of the observer library.

This mixin allows to define event handlers dynamically, without having to create an Observer class for each handler.

For example, assuming button is an instance of some observable class:

count = 0
button.on(:clicked) do
  count += 1
  puts "I have been clicked #{count} times"
end

Events can be fired with the fire method, and support arbitrary arguments.

Instance Method Summary collapse

Instance Method Details

#fire(e) ⇒ Object

Fire an event.

Parameters:

  • e (Symbol, Hash)

    event and arguments. This needs to be either a Symbol, or a Hash with a single key corresponding to the event, and the value being the event data to pass to the handler.



125
126
127
128
# File 'lib/rui/observer_utils.rb', line 125

def fire(e)
  changed
  notify_observers any_to_event(e)
end

#observe(event, &blk) ⇒ Object

Create a dynamic observer handling a given event.

Parameters:

  • event (Symbol)

    the event to handle

  • &blk (Block)

    event handler

Returns:

  • an observer object, which can be later used to remove the event handler.



94
95
96
97
98
99
# File 'lib/rui/observer_utils.rb', line 94

def observe(event, &blk)
  obs = SimpleObserver.new(event, &blk)
  add_observer obs
  # return observer so that we can remove it later
  obs
end

#observe_limited(event, &blk) ⇒ Object

Create a limited observer handling a given event.

A limited observer behaves similarly to a normal dynamic observer, but in addition, it keeps track of the return valur of the handler. When the handler returns true, the observer is destroyed.

Parameters:

  • event (Symbol)

    the event to handle

  • &blk (Block)

    event handler

Returns:

  • an observer object, which can be later used to remove the event handler.



112
113
114
115
116
# File 'lib/rui/observer_utils.rb', line 112

def observe_limited(event, &blk)
  obs = LimitedObserver.new(self, event, &blk)
  add_observer obs
  obs
end

#on(event, &blk) ⇒ Object

Alias to observe.



82
83
84
# File 'lib/rui/observer_utils.rb', line 82

def on(event, &blk)
  observe(event, &blk)
end