View Source Tamnoon.MethodManager (Tamnoon v1.0.0-rc.3)

This module handles the management of different methods as you create them. Notably, it provides the defmethod/2 macro.

Importing the module

In order to create handlers for the methods you set up, you must import Tamnoon.MethodManager in your methods module. Then, you can use the defmethod/2 macro to implement handling of the methods.

Summary

Functions

Defines a method. Methods are functions that can be triggered via Tamnoon HEEx code (see the Methods guide for more info).

The function used internally by Tamnoon.SocketHandler.websocket_handle/2 to route the requests to the appropriate method handler.

Triggers a method with the given name and payload. An additional timeout (in milliseconds) can be specified to delay the triggering of the method.

Functions

Link to this macro

defmethod(name, list)

View Source (macro)

Defines a method. Methods are functions that can be triggered via Tamnoon HEEx code (see the Methods guide for more info).

Methods receive the state map and a req map. The state is the current state of the app, and req is a map containing info about the invocation - specifically:

  • :value: The invoking element's value.
  • :key: The key given to the method (for example, an element with onclick=@update-name will have "name" as the :key). Is included only when a key is given.
  • :element: The raw HTML of the invoking element.

Methods must return either a tuple of the form {}, {diffs}, {diffs, actions}, or {diffs, actions, new_state} where:

  • diffs: A map containing the changes in the state (will be updated in the client).
  • actions: a list of actions (see Tamnoon.DOM).
  • new_state: A map which will be set as the new state (if not provided, the current state will be automatically merged with diffs).

Under the hood, it defines a function named tmnn_[name]. Functions with this prefix in your methods modules will automatically be added to the possible methods when invoking route_request/3.

Example

defmethod :get do
  key = get_key(req, state)

  if key != nil do
    {%{key => state[key]}, [], state}
  else
    {%{tmnn_error: "Error: get method failed as key #{key} not found in the state"}, [], state}
  end
end
Link to this function

route_request(methods_modules, payload, state)

View Source
@spec route_request([module()], map(), map()) ::
  {:reply, {:text, return_value :: String.t()}, new_state :: map()}

The function used internally by Tamnoon.SocketHandler.websocket_handle/2 to route the requests to the appropriate method handler.

Link to this function

trigger_method(method_name, payload, timeout_ms \\ 0)

View Source
@spec trigger_method(atom(), map(), non_neg_integer()) ::
  :ok | :noconnect | :nosuspend | reference()

Triggers a method with the given name and payload. An additional timeout (in milliseconds) can be specified to delay the triggering of the method.