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



57
58
59
60
61
62
63
# File 'lib/wee/callback.rb', line 57

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

#each_triggered_call_with_value(object) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/wee/callback.rb', line 65

def each_triggered_call_with_value(object)
  if ary = @obj_map[object]
    for id in ary
      @callbacks[id].call(@triggered[id]) if @triggered.has_key?(id)
    end
  end
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  @callbacks.empty?
end

#first_triggered(object) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/wee/callback.rb', line 73

def first_triggered(object)
  if ary = @obj_map[object]
    for id in ary
	  return @callbacks[id] if @triggered.has_key?(id)
    end
  end
  return nil
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.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/wee/callback.rb', line 35

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



16
17
18
19
20
21
22
# File 'lib/wee/callback.rb', line 16

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

#reset_triggeredObject



53
54
55
# File 'lib/wee/callback.rb', line 53

def reset_triggered
  @triggered = nil
end

#unregister(object) ⇒ Object



24
25
26
27
28
# File 'lib/wee/callback.rb', line 24

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