We are already aware of the numerous advantages that comes with JavaScript (JS) based action chains.

In this blog, I will highlight how to write and use custom JavaScript functions inside an action chain. Using this approach we can

  • Improve inital application/page load time as source code for action chains are deferred and fetched on ad hoc.
  • Move specific logic inside reusalble funtions and refer it within action chain.
  • Write much cleaner and maintainable code.
  • Page or application level JS file will not be populated with functions that are specfic for an action chain.

Since the JS based action chain is based on the vanilla JavaScript class, so all the benfits and featues that comes in built with JavaScript class can be leveraged. Let's see a sample use case.


Step 1: Create a JS based action.

By default, we have a run method in the action chain which will be invoked when action chain is called.
Let's assume, we have received a message from an API and the message needs to be converted to init cap before assigning to variables.

define([
  "vb/action/actionChain",
  "vb/action/actions",
  "vb/action/actionUtils",
], (ActionChain, Actions, ActionUtils) => {
  "use strict";

  class DisplayInitCap extends ActionChain {
    /**
     * @param {Object} context
     */
    async run(context) {
      const { $page, $flow, $application, $constants, $variables } = context;

      //Messages received from REST API
      const message = "visual builder is a javas script based framework";
      const message2 = 'visual builder uses jet core components';
    }
  }
  return DisplayInitCap;
});

Step 2: Write a custom JS function inside the action chain
 

The custom JS function initCap, is referenced in the run function using this keyword in multiple places.

define([
  "vb/action/actionChain",
  "vb/action/actions",
  "vb/action/actionUtils",
], (ActionChain, Actions, ActionUtils) => {
  "use strict";

  class DisplayInitCap extends ActionChain {
    /**
     * @param {Object} context
     */
    async run(context) {
      const { $page, $flow, $application, $constants, $variables } = context;

      //Messages received from REST API
      const message = 'visual builder is a java script based framework';
      const message2 = 'visual builder uses jet core components';

      //Invoke initCap function
      $page.variables.formattedText = this.initCap(message);
      $page.variables.formattedText2 = this.initCap(message2);
    }

    /**
     * Function to convert message to initcap
     * @param {String} message
     * @return {String} value returned in initcap
     */
    initCap(message) {
      const msgs = message.split(' ');
      return msgs.map(el => `${el[0].toUpperCase()}${el.slice(1)}`).join(' ');
    }
  }
  return DisplayInitCap;
});

Conclusion:

In this blog we have seen, how we can write custom JavaScript functions inside an action chain and leverage complete advantage of JavaScript class.