Class: UIControl

Inherits:
Object show all
Defined in:
lib/sugarcube/uicontrol.rb

Overview

Additions to UIControl to support jQuery-style on and off methods.

Instance Method Summary collapse

Instance Method Details

#off(*events) ⇒ Object

Removes all events that were bound with on. See symbol.rb for the uicontrolevent constant aliases.

Examples:

button.off(:touch)
button.off(:touchupoutside, :touchcancel)
button.off  # all events


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sugarcube/uicontrol.rb', line 34

def off(*events)
  if events.length == 0
    events = sugarcube_callbacks.keys
  end

  events.each do |event|
    event = event.uicontrolevent unless event.is_a? Fixnum

    sugarcube_callbacks[event].each do |handler|
      self.removeTarget(handler, action:'call:event:', forControlEvents:event)
    end
    sugarcube_callbacks.delete(event)
  end
  self
end

#on(*events, &block) ⇒ Object

Add event handlers to UIControls. See symbol.rb for the uicontrolevent constant aliases.

Examples:

button = UIButton.alloc.initWithFrame([0, 0, 10, 10])
button.on(:touch) { my_code }
button.on(:touchupoutside, :touchcancel) { my_code }
# up to two arguments can be passed in
button.on(:touch) { |sender,touch_event| my_code }


13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/sugarcube/uicontrol.rb', line 13

def on(*events, &block)
  handler = SugarCube::UIControlCallbackHelper.new
  handler.callback = block

  events.each do |event|
    event = event.uicontrolevent unless event.is_a? Fixnum

    sugarcube_callbacks[event].push(handler)
    addTarget(handler, action:'call:event:', forControlEvents:event)
  end

  self
end

#sugarcube_callbacksObject

event blocks need to be retained, and the addTarget method explicitly does not retain target. This makes sure that callbacks are retained by pushing the block onto a stack.



54
55
56
# File 'lib/sugarcube/uicontrol.rb', line 54

def sugarcube_callbacks
  @sugarcube_callbacks ||= Hash.new { |hash, key| hash[key] = [] }
end