Custom UI Control Script File

Each custom control requires a script file. The script file must have the same name as the corresponding meta definition file, but with a .js extension. For example, if the meta definition file for the control is magical.json, name the script magical.js.

The script file name can include only alphanumeric or underscore characters. Put the script file at the same location as its corresponding meta definition file. For example, for a control named magical, you could include the meta definition file and the script file at the following location:

mycartridge/cartridge/experience/editors/com/sfcc/magical.json

mycartridge/cartridge/experience/editors/com/sfcc/magical.js

In the script file, you can optionally implement the init function to initialize the custom control with server-side logic or resources.

Note: Every custom control requires a script file. If you don't use the script file to implement the init function, you must include an empty script file in the cartridge.

This example script file, named magical.js, adds options for the control that were not included in the editor_definition of the component's meta definition file, as well as localization information, and additional CSS resources that are required only if the list of unicorns includes more than 10 items. The editor object passed to the init function is of type dw.experience.CustomEditor. It provides access to:

magical.js
'use strict';
 
var Resource = require('dw/web/Resource');
var HashMap = require('dw/util/HashMap');
 
module.exports.init = function (editor) {
  // add some more options programmatically
  editor.configuration.options.put('init', [
    'Wynstar',
    'Jasper',
    'Joshi',
    'Rainbow',
    'Blythe',
    'Mika',
    'Nightwind',
    'Cadillac',
    'Julius',
    'Calimerio'
  ]);
 
  // add some localizations
  var localization = {
    placeholder: 'Select your favorite unicorn',
    description: 'Unicorns are magical creatures you want for every component. Select the one of your choice now!',
    group1: 'Unicorns from JSON Config',
    group2: 'Unicorns from init()',
    group3: 'Unicorns from OCAPI request'
  };
  editor.configuration.put('localization', Object.keys(localization).reduce(function (acc, key) {
    acc.put(key, Resource.msg(key, 'experience.editors.com.sfcc.magical', localization[key]));
    return acc;
  }, new HashMap()));
 
  // add some resources only required for a lot of unicorns
  if ((editor.configuration.options.config.length + editor.configuration.options.init.length) > 10) {
     editor.resources.styles.push("/experience/editors/com/sfcc/magical-extreme.css");
  }
}