-
Notifications
You must be signed in to change notification settings - Fork 1
/
Button.ts
87 lines (77 loc) · 2.1 KB
/
Button.ts
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
import { TouchEvent } from "../event";
import { Component } from "./Component";
/**
* 处理点击事件
* ```ts
* // 创建节点
* const node = new Transform();
* // 添加布局组件
* const button = node.addComponent(Button);
* const target = this;
* function onClick() {
* console.log('click');
* button.remove(onClick, target);
* }
* // 添加点击事件
* button.add(onClick, target)
* // 放入父节点
* parent.addChild(node);
* ```
*/
export class Button extends Component {
start(): void {
this.node.touch = true;
this.node.deliver = false;
this.node.emitter.on(TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
this.node.emitter.on(TouchEvent.TOUCH_END, this.onTouchEnd, this);
}
/**
* 记录销毁点击事件的计时
*/
private timeout?: NodeJS.Timeout;
/**
* 触摸开始
*/
private onTouchBegin() {
/**
* 当经过设定的点击时间间隔后,认为不能触发点击(此设定可做双击)
*/
this.timeout = setTimeout(() => {
this.node.emitter.on(TouchEvent.TOUCH_END, this.onTouchEnd, this);
}, this.difftime);
}
private onTouchEnd() {
clearTimeout(this.timeout);
this.callback.forEach((value, target) => {
value.forEach((func) => {
func.apply(target);
});
});
}
/**
* 起落时间间隔
*/
difftime = 200;
callback = new Map<any, Function[]>();
add(callback: Function, target: any) {
if (!this.callback.has(target)) {
this.callback.set(target, []);
}
const func = this.callback.get(target);
func.push(callback);
}
remove(callback: Function, target: any) {
if (!this.callback.has(target)) {
return;
}
const func = this.callback.get(target);
const index = func.indexOf(callback);
if (index == -1) {
return;
}
func.splice(index, 1);
if (func.length == 0) {
this.callback.delete(target);
}
}
}