-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbutton.lua
106 lines (89 loc) · 2.64 KB
/
button.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
--[[
A generic button class
This code is MIT licensed, see http://www.opensource.org/licenses/mit-license.php
(C) 2010 - 2011 Gideros Mobile
]]
Button = gideros.class(Sprite)
function Button:init(upState, downState)
self.upState = upState
self.downState = downState
self.focus = false
-- set the visual state as "up"
self:updateVisualState(false)
-- register to all mouse and touch events
self:addEventListener(Event.MOUSE_DOWN, self.onMouseDown, self)
self:addEventListener(Event.MOUSE_MOVE, self.onMouseMove, self)
self:addEventListener(Event.MOUSE_UP, self.onMouseUp, self)
self:addEventListener(Event.TOUCHES_BEGIN, self.onTouchesBegin, self)
self:addEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
self:addEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
self:addEventListener(Event.TOUCHES_CANCEL, self.onTouchesCancel, self)
end
function Button:onMouseDown(event)
if self:hitTestPoint(event.x, event.y) then
self.focus = true
self:updateVisualState(true)
event:stopPropagation()
end
end
function Button:onMouseMove(event)
if self.focus then
if not self:hitTestPoint(event.x, event.y) then
self.focus = false
self:updateVisualState(false)
end
event:stopPropagation()
end
end
function Button:onMouseUp(event)
if self.focus then
self.focus = false
self:updateVisualState(false)
self:dispatchEvent(Event.new("click")) -- button is clicked, dispatch "click" event
event:stopPropagation()
end
end
-- if button is on focus, stop propagation of touch events
function Button:onTouchesBegin(event)
if self.focus then
event:stopPropagation()
end
end
-- if button is on focus, stop propagation of touch events
function Button:onTouchesMove(event)
if self.focus then
event:stopPropagation()
end
end
-- if button is on focus, stop propagation of touch events
function Button:onTouchesEnd(event)
if self.focus then
event:stopPropagation()
end
end
-- if touches are cancelled, reset the state of the button
function Button:onTouchesCancel(event)
if self.focus then
self.focus = false;
self:updateVisualState(false)
event:stopPropagation()
end
end
-- if state is true show downState else show upState
function Button:updateVisualState(state)
if state then
if self:contains(self.upState) then
self:removeChild(self.upState)
end
if not self:contains(self.downState) then
self:addChild(self.downState)
end
else
if self:contains(self.downState) then
self:removeChild(self.downState)
end
if not self:contains(self.upState) then
self:addChild(self.upState)
end
end
end