Class: Wee::CallbackRegistry

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

Instance Method Summary collapse

Constructor Details

#initialize(prefix = "") ⇒ CallbackRegistry

Returns a new instance of CallbackRegistry.



4
5
6
7
8
9
10
# File 'lib/wee/callback.rb', line 4

def initialize(prefix="")
  @prefix = prefix
  @next_id = 0
  @callbacks = {}    # {callback_id1 => callback1, callback_id2 => callback2}
  @triggered = nil
  @obj_map = {}      # obj => [callback_id1, callback_id2, ...]
end

Instance Method Details

#each_triggered(object) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/wee/callback.rb', line 53

def each_triggered(object)
  if ary = @obj_map[object]
    ary.each do |id|
      yield @callbacks[id], @triggered[id] if @triggered.has_key?(id)
    end
  end
end

#prepare_triggered(ids_and_values) ⇒ Object

NOTE that if fields named “xxx” and “xxx.yyy” occur, the value of @fields is { nil => …, ‘yyy’ => … }. This is required to make image buttons work correctly.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/wee/callback.rb', line 31

def prepare_triggered(ids_and_values)
  @triggered = {}
  ids_and_values.each do |id, value|
    if id =~ /^#{@prefix}(\d+)([.](.*))?$/
      id, suffix = Integer($1), $3
      next unless @callbacks[id]

      if @triggered[id].kind_of?(Hash)
        @triggered[id][suffix] = value
      elsif suffix
        @triggered[id] = {nil => @triggered[id], suffix => value}
      else
        @triggered[id] = value
      end
    end
  end
end

#register(object, callback) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/wee/callback.rb', line 12

def register(object, callback)
  id = @next_id
  @next_id += 1
  @callbacks[id] = callback
  (@obj_map[object] ||= []) << id
  return "#{@prefix}#{id}"
end

#reset_triggeredObject



49
50
51
# File 'lib/wee/callback.rb', line 49

def reset_triggered
  @triggered = nil
end

#unregister(object) ⇒ Object



20
21
22
23
24
# File 'lib/wee/callback.rb', line 20

def unregister(object)
  if arr = @obj_map.delete(object)
    arr.each {|id| @callbacks.delete(id) }
  end
end