-
Notifications
You must be signed in to change notification settings - Fork 0
/
adv-menu-delegation-class.html
58 lines (48 loc) · 1.4 KB
/
adv-menu-delegation-class.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>
<body>
<div id="menu">
<button data-action="save">Save</button>
<button data-action="load">Load</button>
<button data-action="search">Search</button>
</div>
<script>
class Menu {
constructor(elem) {
console.log('this: ', this)
this.elem = elem
console.log('this.elem: ', this.elem)
console.log('this.onClick.bind(this): ', this.onClick.bind(this)) // (*)
//bind the elem's onclick event to the class onClick method
elem.onclick = this.onClick.bind(this)
// can also work with other DOM events - e.g.,
// elem.onmouseover = this.onClick.bind(this)
}
save() {
alert('saving')
}
load() {
alert('loading')
}
search() {
alert('searching')
}
#sayHello(action) {
console.log('called from sayHello: ', action)
}
onClick(event) {
let action = event.target.dataset.action
console.log('action:', action)
if (action) {
this[action]()
console.log('this[action]():', this[action])
this.#sayHello(action)
}
}
}
//since id is unique to the DOM you can simply use it to instantiate the class
new Menu(menu)
// you can also instantiate the class using a selector
// const test = document.querySelector('#menu')
// new Menu(test)
</script>
</body>