Skip to content
This repository was archived by the owner on Apr 30, 2019. It is now read-only.

Commit dd8e145

Browse files
authored
Expose Value member of Callback struct (#9)
Issue: #7
1 parent 4ea103e commit dd8e145

File tree

1 file changed

+36
-31
lines changed

1 file changed

+36
-31
lines changed

js/js_notwasm.go

Lines changed: 36 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ func Undefined() Value {
2626
}
2727

2828
type Callback struct {
29-
f func([]Value)
30-
flags EventCallbackFlag
29+
Value
3130
}
3231

3332
type EventCallbackFlag int
@@ -38,8 +37,39 @@ const (
3837
StopImmediatePropagation
3938
)
4039

40+
func funcToValue(flags EventCallbackFlag, f func([]Value)) Value {
41+
return Value{
42+
v: id.Invoke(func(args ...*js.Object) {
43+
if len(args) > 0 {
44+
e := args[0]
45+
if flags&PreventDefault != 0 {
46+
e.Call("preventDefault")
47+
}
48+
if flags&StopPropagation != 0 {
49+
e.Call("stopPropagation")
50+
}
51+
if flags&StopImmediatePropagation != 0 {
52+
e.Call("stopImmediatePropagation")
53+
}
54+
}
55+
56+
// Call the function asyncly to emulate Wasm's Callback more
57+
// precisely.
58+
go func() {
59+
newArgs := []Value{}
60+
for _, arg := range args {
61+
newArgs = append(newArgs, Value{v: arg})
62+
}
63+
f(newArgs)
64+
}()
65+
}),
66+
}
67+
}
68+
4169
func NewCallback(f func([]Value)) Callback {
42-
return Callback{f: f}
70+
return Callback{
71+
Value: funcToValue(0, f),
72+
}
4373
}
4474

4575
func NewEventCallback(flags EventCallbackFlag, fn func(event Value)) Callback {
@@ -48,12 +78,12 @@ func NewEventCallback(flags EventCallbackFlag, fn func(event Value)) Callback {
4878
fn(e)
4979
}
5080
return Callback{
51-
f: f,
52-
flags: flags,
81+
Value: funcToValue(flags, f),
5382
}
5483
}
5584

5685
func (c Callback) Release() {
86+
c.Value = Null()
5787
}
5888

5989
type Error struct {
@@ -85,32 +115,7 @@ func ValueOf(x interface{}) Value {
85115
case Value:
86116
return x
87117
case Callback:
88-
return Value{
89-
v: id.Invoke(func(args ...*js.Object) {
90-
if len(args) > 0 {
91-
e := args[0]
92-
if x.flags&PreventDefault != 0 {
93-
e.Call("preventDefault")
94-
}
95-
if x.flags&StopPropagation != 0 {
96-
e.Call("stopPropagation")
97-
}
98-
if x.flags&StopImmediatePropagation != 0 {
99-
e.Call("stopImmediatePropagation")
100-
}
101-
}
102-
103-
// Call the function asyncly to emulate Wasm's Callback more
104-
// precisely.
105-
go func() {
106-
newArgs := []Value{}
107-
for _, arg := range args {
108-
newArgs = append(newArgs, Value{v: arg})
109-
}
110-
x.f(newArgs)
111-
}()
112-
}),
113-
}
118+
return x.Value
114119
case nil:
115120
return Null()
116121
case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, unsafe.Pointer, string, []byte:

0 commit comments

Comments
 (0)