Skip to main content

JavaScript functions

Use a function to transform a value or incoming data when standard configuration does not cover the required operation. For navigation, signal commands, or setting a value directly, start with the built-in Actions.

Choose where the function belongs​

UseLocationWhere to select it
Reusable project functionfunctions/*.js, with subfolders allowedA Function action or a supported formatter picker.
Variable value formatterProject function or a predefined formatterFormatter function in the variables editor.
Datasource transformationA JavaScript file beside the .datasource fileDatasource format function in the datasource Forms Editor.

Creating a function file makes it available to the project. It does not automatically attach it to a variable, datasource, or event. Select it in the relevant consuming configuration and test that configuration.

Create a function in VS Code​

  1. Open your AVstudio project.
  2. Open the Command Palette with ⇧⌘P / Ctrl+Shift+P and run AVstudio: Add function. You can also use Add function from the functions folder's context menu.
  3. At Enter name for new function, enter a meaningful name such as clampVolume.
  4. NG creates functions/clampVolume.js and opens it in the JavaScript editor.
  5. Replace the generated body with your implementation and give the function a descriptive JavaScript name.
  6. Save with ⌘S / Ctrl+S and resolve any syntax diagnostics before selecting it elsewhere.

The 27.0.29 template uses function myFunction(data) even when the file has another name. Rename the declaration as part of editing the example; the filename and JavaScript declaration are separate names.

The 27.0.29 template keeps that named-function contract and adds a commented window.avstudio API hint block. The JavaScript editor's AVstudio API Functions context submenu inserts method snippets. Use the runtime API reference for navigation, publishing signals, feedback, datasource reads, and variable writes.

clampVolume.js opened in the VS Code JavaScript editor with the functions folder visible

Functions are edited as source code. The Element Properties panel configures visual controls; it is not a form for editing the function body. Use Explorer to locate and reopen your .js file.

Function contract​

Use one named, synchronous JavaScript function that accepts input and returns the result:

function myFunction(data) {
return data;
}

Keep this format export-free and dependency-free: do not add import, export, require, or external packages. Use a direct result rather than an asynchronous operation or a Promise. The caller determines what data contains, so inspect the expected value or payload before writing the transformation.

PartMeaning
Function nameA readable JavaScript identifier describing the transformation.
dataThe value or payload supplied by the consuming feature. Do not assume every caller provides a number or an array.
returnThe transformed result. Every intended path should return a value of the shape/type the consumer expects.
Saved file referenceThe reference selected by NG when attaching the function. Use the picker rather than guessing an identifier.

Example: constrain volume to 0–100​

The sample converts its input to a number, limits finite numbers to the range 0–100, and uses 0 for non-finite results:

function clampVolume(data) {
const value = Number(data);
return Number.isFinite(value)
? Math.max(0, Math.min(100, value))
: 0;
}
InputReturned valueReason
2525Already inside the range.
"75"75Numeric text is converted to a number.
-100Below the minimum.
150100Above the maximum.
"invalid"0Conversion is not a finite number.
null or ""0JavaScript numeric conversion yields zero.

This is a deliberate input policy for the example. If empty input should mean “unknown” rather than zero, check for empty/null input before numeric conversion and define a compatible result for the consumer.

Attach it to a variable​

  1. Open global.variables in AVS Forms Editor.
  2. Find the number variable volume. Create it first if it does not exist.
  3. In that row's Formatter function column, open the selector.
  4. Under Global Functions, select clampVolume.js.
  5. Save the variables document.
  6. In Live Preview, exercise the path that updates the variable and inspect the formatted result, for example through a Text element bound to $volume$.

Global Variables in VS Code with clampVolume.js selected as the volume formatter

The sample saves the selection as "formatValueFunctionUid": "functions/clampVolume.js". The schema calls this field a UID, but the observed saved reference is a project-relative path. Let the editor write the reference instead of inventing a hash or copying an identifier from another project.

The picker also exposes Predefined Formatters, including Add floating point, Format seconds to time, Toggle boolean-like numbers (0-1), and Number to toggled boolean in this build. Check these options before creating a custom function for a common transformation.

Selecting the formatter does not change the variable's declared type. Return a number for a number variable, and test actual value updates rather than assuming the displayed default value proves the formatter ran. See Variables and parameters for the surrounding variable workflow.

Select a function in an action​

  1. Select the element that owns the event and open Element Properties → Actions → Create Action.
  2. Give the action a name and choose a supported Behaviour.
  3. Select the Function tab and choose the saved function from its picker.
  4. Configure any input/value options offered for that event.
  5. Choose Save action & close, save the page, and test the event in Live Preview.

A Function action stores its selected reference in attachedFunctionToRun. A formatter and a Function action serve different purposes: the formatter transforms a value for its consumer, while the action invokes the function in response to an event. Do not assume returning 50 from an action function automatically writes 50 to a variable or sends an analog command. Use the corresponding Variable or signal action when that is the desired result.

For an On Change action, distinguish the event's changed value from a configured custom literal. Verify what input reaches the function. See Actions for event selection, value handling, and the AVS Actions form.

Datasource formatters​

Use a datasource formatter to adapt the incoming payload to the structure your interface expects. Place the file beside its .datasource configuration, then select it in Datasource format function. The stored formatterFunction reference can be relative, such as ./normalizeRooms.js.

For a source that may provide an array directly or an object containing a rooms array:

function normalizeRooms(data) {
if (Array.isArray(data)) return data;
if (data && Array.isArray(data.rooms)) return data.rooms;
return [];
}

This function returns an array on every path, making its outer shape suitable for a Subpage List. It does not validate each record's fields; the consuming card still needs the fields used by its bindings. An unexpected payload becomes an empty list under this policy, so inspect source errors separately rather than interpreting every empty list as “no rooms.”

After saving and selecting the formatter, open the consuming element's Edit datasource filters view and inspect the resulting data. Use filter steps for simple picking and filtering; use JavaScript when the transformation needs logic beyond those operations. See Datasources and JSON filters for that workflow.

Validate changes​

Function execution in installed builds was fixed in 27.0.23. If an older project appeared to ignore a formatter, update the extension and retest the selected consumer; the 27.0.29 source contract remains synchronous and export-free.

Check the function at two levels:

  1. Transformation: try expected input, boundary values, null/empty data, and invalid types. Verify both the returned value and its type.
  2. Integration: confirm the saved function is selected by the correct variable, datasource, or action, then exercise that consumer in Live Preview.

Save all changed documents, resolve diagnostics, and run Run Project Health Check. A function that works with a manually supplied value can still be attached to the wrong consumer or receive a different runtime payload.

SymptomWhat to check
Function is missing from the pickerSave the file, check its folder and syntax, and confirm that the picker lists the relevant kind of function. Datasource formatters and global functions have different selection contexts.
Renamed function no longer runsReopen each consuming configuration and reselect the file so its saved reference matches.
Result is undefinedCheck that every code path returns a result.
Variable has an unexpected typeInspect numeric conversion and the declared variable type. A formatted label is not the same as a numeric value.
Subpage List is emptyCheck that the formatter returns an array and that its records contain the mapped fields.
Function action does not change a variableInvocation alone is not a variable assignment. Check the chosen action type and intended destination.
No visible change after saving codeVerify the consuming reference and trigger the actual update/event in Live Preview.