From 9faa609930fdff016d0ca5ce8dafed9198531c30 Mon Sep 17 00:00:00 2001 From: Chan Wen Xu Date: Sun, 21 Mar 2021 21:38:39 +0800 Subject: [PATCH] fix: Use function wrapper provided by JS --- wasm/function.go | 4 ++-- wasm/wasm.go | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/wasm/function.go b/wasm/function.go index a509c85..5b29f35 100644 --- a/wasm/function.go +++ b/wasm/function.go @@ -27,7 +27,7 @@ func toJSFunc(x reflect.Value) js.Value { hasError = funcType.Out(funcType.NumOut()-1) == errorType } - return js.FuncOf(func(this js.Value, args []js.Value) interface{} { + return funcWrapper.Invoke(js.FuncOf(func(this js.Value, args []js.Value) interface{} { in, err := conformJSValueToType(funcType, this, args) if err != nil { return ToJSValue(goThrowable{ @@ -52,7 +52,7 @@ func toJSFunc(x reflect.Value) js.Value { return ToJSValue(goThrowable{ Result: returnValue(out[:len(out)-1]), }) - }).JSValue() + })) } var jsValueType = reflect.TypeOf(js.Value{}) diff --git a/wasm/wasm.go b/wasm/wasm.go index 56d94c2..3e9f8e4 100644 --- a/wasm/wasm.go +++ b/wasm/wasm.go @@ -1,12 +1,18 @@ package wasm +import "syscall/js" + // Magic values to communicate with the JS library. const ( - globalIdent = "__go_wasm__" - readyHint = "__ready__" + globalIdent = "__go_wasm__" + readyHint = "__ready__" + funcWrapperName = "__wrapper__" ) -var bridge Object +var ( + bridge Object + funcWrapper js.Value +) func init() { bridgeJS, err := Global().Get(globalIdent) @@ -18,6 +24,11 @@ func init() { if err != nil { panic("JS wrapper " + globalIdent + " is not an object") } + + funcWrapper, err = bridge.Get(funcWrapperName) + if err != nil { + panic("JS wrapper " + globalIdent + "." + funcWrapperName + " not found") + } } // Ready notifies the JS bridge that the WASM is ready.