-
Notifications
You must be signed in to change notification settings - Fork 5
/
event.go
119 lines (105 loc) · 2.37 KB
/
event.go
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
107
108
109
110
111
112
113
114
115
116
117
118
119
package domui
import (
"sync"
"sync/atomic"
"syscall/js"
"github.com/reusee/dscope"
)
var elementID int32 = 42
type EventSpec struct {
Event string
Func any
}
func (_ EventSpec) IsSpec() {}
func On(ev string) func(cb any) EventSpec {
return func(cb any) EventSpec {
return EventSpec{
Event: ev,
Func: cb,
}
}
}
var (
eventRegistryLock sync.RWMutex
eventRegistry = make(map[int32]map[string][]EventSpec)
eventHandlerSet = make(map[string]bool)
)
var eventHandlerScope = dscope.New()
func setEventSpecs(wrap js.Value, element js.Value, specs map[string][]EventSpec) {
idValue := element.Get("__element_id__")
var id int32
if idValue.IsUndefined() {
id = atomic.AddInt32(&elementID, 1)
element.Set("__element_id__", id)
} else {
id = int32(idValue.Int())
}
for event := range specs {
if eventHandlerSet[event] {
continue
}
wrap.Call(
"addEventListener",
event,
js.FuncOf(
func(this js.Value, args []js.Value) any {
go func() {
ev := args[0]
typ := ev.Get("type").String()
bubbles := ev.Get("bubbles").Bool()
for node := ev.Get("target"); !node.IsNull() && !node.IsUndefined() && !node.Equal(wrap); node = node.Get("parentNode") {
idValue := node.Get("__element_id__")
if idValue.IsUndefined() {
if !bubbles {
break
}
continue
}
id := int32(idValue.Int())
eventRegistryLock.RLock()
var specs []EventSpec
if evs, ok := eventRegistry[id]; ok {
if ss, ok := evs[typ]; ok {
specs = append(ss[:0:0], ss...)
}
}
eventRegistryLock.RUnlock()
for _, spec := range specs {
eventHandlerScope.Fork(
func() js.Value {
return node
},
).Call(spec.Func)
}
if !bubbles {
break
}
}
}()
return nil
},
),
true,
)
eventHandlerSet[event] = true
}
eventRegistryLock.Lock()
eventRegistry[id] = specs
eventRegistryLock.Unlock()
}
func unsetEventSpecs(element js.Value) {
idValue := element.Get("__element_id__")
var id int32
if idValue.IsUndefined() {
return
} else {
id = int32(idValue.Int())
}
eventRegistryLock.Lock()
eventRegistry[id] = nil
eventRegistryLock.Unlock()
childNodes := element.Get("childNodes")
for i := childNodes.Length() - 1; i >= 0; i-- {
unsetEventSpecs(childNodes.Index(i))
}
}