Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang's syscall/js js.NewCallback is undefined

I am new to both go and wasm and it looks like these projects are pretty fast moving. I was reading an introduction to using wasm in go and it seems although it was written in January, its already out of date.

I am attempting to call a single go function when a JavaScript function is invoked. The example says to do something like this:

 js.Global().Set("jsFunctionName", js.NewCallback(goCallback))

Although when I am trying to compile this, I am getting this error:

./webassembly.go:54:35: undefined: js.NewCallback

I checked the documentation and see no reference to NewCallback. What is the current "correct" way that this should be done?

like image 714
w33t Avatar asked Apr 22 '19 19:04

w33t


People also ask

What is allthreadssyscall in Golang?

AllThreadsSyscall performs a syscall on each OS thread of the Go runtime. It first invokes the syscall on one thread. Should that invocation fail, it returns immediately with the error status. Otherwise, it invokes the syscall on all of the remaining threads in parallel.

Why can't I use syscall/JS in the playground?

Sign in to your account The playground is not using GOOS=js, so it is not able to use the package syscall/js. Examples that depend on syscall/js should not show a "Run" button. Fixes #28526 .

Is it possible to return a value from gocallback?

Note the signature of goCallback has changed and now since Go 1.12, there is a support for return values. For example, here is how to expose a simple add function: Thanks for contributing an answer to Stack Overflow!

How do I call a Go function from JavaScript?

The Go function fn is called with the value of JavaScript's "this" keyword and the arguments of the invocation. The return value of the invocation is the result of the Go function mapped back to JavaScript according to ValueOf. Invoking the wrapped Go function from JavaScript will pause the event loop and spawn a new goroutine.


1 Answers

js.Global().Set("jsFunctionName", js.NewCallback(goCallback))

should be as:

js.Global().Set("jsFunctionName", js.FuncOf(goCallback))

Note the signature of goCallback has changed and now since Go 1.12, there is a support for return values. For example, here is how to expose a simple add function:

// function definition
func add(this js.Value, i []js.Value) interface{} {
  return js.ValueOf(i[0].Int()+i[1].Int())
}

// exposing to JS
js.Global().Set("add", js.FuncOf(add))
like image 191
gogaman Avatar answered Oct 16 '22 09:10

gogaman