Denox.CallbackHandler (denox v0.7.0)

Copy Markdown View Source

GenServer that handles JS → Elixir callbacks for a Denox runtime.

When JavaScript code calls Denox.callback(name, arg1, arg2, ...), this handler receives the request, invokes the registered Elixir function, and sends the result back to JavaScript.

Usage

# 1. Start a callback handler with named functions
{:ok, handler} = Denox.CallbackHandler.start_link(
  callbacks: %{
    "greet" => fn [name] -> "Hello, #{name}!" end,
    "add" => fn [a, b] -> a + b end
  }
)

# 2. Create a runtime with the handler's PID
{:ok, rt} = Denox.runtime(callback_pid: handler)

# 3. JavaScript can now call back to Elixir
{:ok, result} = Denox.eval(rt, ~s[Denox.callback("greet", "Alice")])
# result => ""Hello, Alice!""

Convenience

Use Denox.CallbackHandler.runtime/1 to create both handler and runtime in one call:

{:ok, rt, handler} = Denox.CallbackHandler.runtime(
  callbacks: %{"add" => fn [a, b] -> a + b end},
  base_dir: "/some/path"
)

Summary

Functions

Returns a specification to start this module under a supervisor.

Create a callback handler and runtime together.

Start a callback handler.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

runtime(opts)

@spec runtime(keyword()) :: {:ok, Denox.runtime(), pid()} | {:error, String.t()}

Create a callback handler and runtime together.

Options:

  • :callbacks - map of callback name to function (required)
  • All other options are passed to Denox.runtime/1

Returns {:ok, runtime, handler_pid} or {:error, reason}.

start_link(opts)

@spec start_link(keyword()) :: GenServer.on_start()

Start a callback handler.

Options:

  • :callbacks - map of callback name (string) to function (required). Each function receives a list of decoded JSON arguments.