Handle a browser event with a wire

Use scomp#wire to connect a browser event to an action or a server postback. Give the target element a stable ID within the rendered page.

Use scomp#wire to connect a browser event to an action or a server postback. Give the target element a stable ID within the rendered page.

<button id="show-help" type="button">{_ Show help _}</button>
<div id="garden-help" style="display:none">{_ Choose a sunny spot. _}</div>
{% wire id="show-help" action={show target="garden-help"} %}

Use a server postback when the action needs server data or writes content. A client-side action alone cannot authorize a write. Check the browser console and the server logs when an event appears to do nothing.

Use a base template with the standard JavaScript includes and a final {% script %}; enable mod_wires on the site. Put the example inside its content block. Click Show help and expect the hidden text to appear without navigation. If this partial can appear twice, use generated template IDs such as #show_help rather than repeating the literal ID.

Handle a postback on the server

Use the active Garden module as the delegate. Add this header, export, and callback to mod_garden.erl, merging with declarations and event clauses already present:

-include_lib("zotonic_core/include/zotonic.hrl").
-export([event/2]).

-spec event(Event, Context) -> z:context()
    when Event :: #postback{}, Context :: z:context().
event(#postback{message = {garden_hello, []}}, Context) ->
    z_render:growl(?__("Welcome to the garden", Context), Context).

In a page with the standard JavaScript includes, mod_wires, and a final {% script %}:

<button id="garden-hello" type="button">{_ Say hello _}</button>
{% wire id="garden-hello" postback={garden_hello} delegate=`mod_garden` %}

Compile and load the module, reload the page, and click the button. Expect the greeting notification. The returned context contains the queued browser response; returning the original context after another response call can lose that response.

This public example changes no stored data. For a write, read only supported binary query keys, validate input, and authorize with the supplied context before calling a model. A signed postback does not make arbitrary form values trustworthy. A form submit delivers #submit{}, not #postback{}.