Skip to content

JavaScript Hooks

Ralf Bitter edited this page Aug 14, 2025 · 4 revisions

ASYNergy allows JavaScript to be executed on certain events.

Hooks Description
message.sent Called when an ASYNergy update triggers a message sent to the server via AJAX.
element.updating Called before ASYNergy updates an element after a network roundtrip.
element.updated Called after ASYNergy updates an element after a network roundtrip.
message.processed Called after ASYNergy processes all side effects from a message.
request Called right before a request is sent.

Examples:

<script>

    document.addEventListener("DOMContentLoaded", () => {

        ASYNergy.hook('message.sent', (agent) => {
          console.log("hook message.sent", agent);
        });

        ASYNergy.hook('element.updating', () => {
          console.log("hook element.updating");
        });

        ASYNergy.hook('element.updated', (mutableEl) => {
          console.log("hook element.updated", mutableEl);
        });

        ASYNergy.hook('message.processed', (mutableEl, agent) => {
          console.log("hook message.processed", mutableEl, agent);
        });
        
        ASYNergy.hook('request', (options, mutables, model) => {
          console.log("hook request", mutables, model);
        });

    });

</script>

The argument of the function parameter named "agent" is the "model" element object including additional properties like asynPayload, actionType, agentID, etc.

The argument of the function parameter named "mutableEl" is the "mutable" element object.

The argument of the function parameter named "options" is an object that currently only has one property "headers", which is itself an object.

The argument of the function parameter named "mutables" is an array containing all mutable elements as objects.

The argument of the function parameter named "model" is the model which triggered the request as an object.


Real world example:

Here is an example of how you can use the request hook to set a custom header.

Let's assume the client sends a JSON Web Token triggered by a click on a button that has an attribute asyn:click with the value "secretdata". This requires a custom header, in this case an "Authorization" header using the "Bearer" schema (Authorization: Bearer <token>).
First, we need to ensure that the header is only set when the corresponding button is clicked. To do this, we check the value of the model attribute. Then we add our custom header to the "headers" object.

<script>

    document.addEventListener("DOMContentLoaded", () => {

        ASYNergy.hook('request', (options, mutables, model) => {
        if (model.modelAttrVal === 'secretdata') {
          options.headers['Authorization'] = 'Bearer ' + <token>;
        } else {
          options.headers = {};
        };
      });

    });

</script>

Clone this wiki locally