我有下面的代码,其中函数正确地附加到按钮onclick
事件:
func f(this js.Value, args []js.Value) interface{} {
println("hello world")
return nil
}
btn.Set("onclick", js.FuncOf(f))
我试图将此函数的参数传递为:
btn.Set("onclick", js.FuncOf(f).Invoke("Hello World"))
并在js.Func
中将其操作为:
for x := range args {
println(x)
}
但我得到了错误:
wasm_exec.js:421 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'exports')
at syscall/js.valueInvoke (wasm_exec.js:421)
at syscall_js.valueInvoke (main.wasm:0x133521)
at syscall_js.Value.Invoke (main.wasm:0x131300)
at main.html (main.wasm:0x25b572)
at main.main (main.wasm:0x25e591)
at runtime.main (main.wasm:0x7f285)
at wasm_pc_f_loop (main.wasm:0xddf81)
at wasm_export_run (main.wasm:0xddf54)
at global.Go.run (wasm_exec.js:577)
at init (wasm.js:7)
有什么想法吗?
我使用.bind
解决了它,如下所示:
element.Set("onclick", js.FuncOf(f).Call("bind", e, args...))
// bind(event, arguments...), passed to function f as (arguments..., event)
所以,我的代码变成:
btn.Set("onclick", js.FuncOf(f).Call("bind", btn, "hi", "hello"))
func f(this js.Value, args []js.Value) interface{} {
for index, item := range args {
if x < len(args)-1 { // len(args)-1 is the event itself
println(index, item.String())
}
}
self := args[len(args)-1].Get("target")
// self = event.target == this
self.Get("style").Call("setProperty", "background-color", "red")
// same as:
// this.Get("style").Call("setProperty", "background-color", "red")
return nil
}