liveBook · Manning

Js.FuncOf

As explained in Learn Go with Pocket-Sized Projects

js.FuncOf is a syscall/js function that wraps a Go function so it can be called from JavaScript.

js.FuncOf wraps a Go function as a js.Func that JavaScript can call. Register it with js.Global().Set or a DOM namespace, then keep the Go program running. section 12.2.2

A callback passed to js.FuncOf receives:

  • this js.Value, representing the DOM element or JavaScript context that made the call. section 12.2.2
  • args []js.Value, containing values supplied by JavaScript. section 12.2.2 section 12.2.3
  • any, allowing the callback to return a value; returning an error causes the js package to panic. section 12.2.2

Expose and call a Go callback

Register generate with js.Global().Set("generate", js.FuncOf(m.generate)), then call generate() from HTML. A multiplication exercise uses the callback to generate operands and update DOM elements. Because the Go program must remain alive, main waits on an unclosed channel; otherwise JavaScript reports that the Go program has already exited.

Pass input arguments

An HTML form calls validate(providedAnswer.value). The Go callback checks len(args), converts args[0].String() with strconv.Atoi, reports invalid input through alert, and validates the multiplication answer.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the callback signature, argument flow, error panic behavior, lifetime requirement, and release-related leak risk.
Examples
Uses multiplication exercises, DOM updates, HTML buttons, form input, numeric parsing, alerts, and namespaced callbacks.
What it assumes
Assumes familiarity with Go methods, HTML, JavaScript calls, DOM access, and WebAssembly startup.
What you can do after
Build it from scratch by exposing Go functions, receiving JavaScript arguments, updating the DOM, and handling browser input.
How it connects
Connects Go callbacks with JavaScript, WebAssembly, the DOM, HTML events, and JavaScript namespaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.