liveBook · Manning

Js.Func

As explained in Learn Go with Pocket-Sized Projects

js.Func is a Go wrapper type representing a JavaScript-callable function in the WebAssembly interoperability API.

js.Func is the wrapper used to expose a Go function to JavaScript through the WebAssembly interoperability API. Create it with js.FuncOf rather than constructing it manually, then register it under a JavaScript name with Set. section 12.2.2

Account for the callback contract and its runtime behavior:

  • Release functions when appropriate, because calling FuncOf too many times can leak resources. section 12.2.2
  • Avoid returning errors directly: the js package turns callback errors into a panic. section 12.2.2

Expose a generate callback

Register a method globally with js.Global().Set("generate", js.FuncOf(m.generate)), then call it from HTML with generate() or a button’s onclick handler.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines creation, callback arguments, registration, process lifetime, error behavior, and release concerns without deeper runtime internals.
Examples
Uses a generate callback, HTML buttons, global registration, and a multiplyApp namespace.
What it assumes
Assumes familiarity with Go methods, JavaScript, HTML, the DOM, and WebAssembly execution.
What you can do after
Operate/configure Go callbacks for JavaScript, including lifetime management and namespaced HTML invocation.
How it connects
Connects JavaScript, WebAssembly, the DOM, callbacks, and Go’s js.Value API.

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.