forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent-handling.html
58 lines (55 loc) · 1.48 KB
/
event-handling.html
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<button id="clickme">Click me: 0</button>
<script>
/* Title: Event Handling
Description: when you pass function A to function B as a parameter, function A is a callback function
*/
// antipattern
/*var b = document.getElementById('clickme'),
count = 0;
b.onclick = function () {
count += 1;
b.innerHTML = "Click me: " + count;
};*/
// preferred
var b = document.getElementById('clickme');
if (document.addEventListener) { // W3C
b.addEventListener('click', myHandler, false);
} else if (document.attachEvent) { // IE
b.attachEvent('onclick', myHandler);
} else { // last resort
b.onclick = myHandler;
}
function myHandler(e) {
var src, parts;
// get event and source element
e = e || window.event;
src = e.target || e.srcElement;
// actual work: update label
parts = src.innerHTML.split(": ");
parts[1] = parseInt(parts[1], 10) + 1;
src.innerHTML = parts[0] + ": " + parts[1];
// no bubble
if (typeof e.stopPropagation === "function") {
e.stopPropagation();
}
if (typeof e.cancelBubble !== "undefined") {
e.cancelBubble = true;
}
// prevent default action
if (typeof e.preventDefault === "function") {
e.preventDefault();
}
if (typeof e.returnValue !== "undefined") {
e.returnValue = false;
}
}
</script>
</body>
</html>