A very good and flexible feature of the Drafts model is that:
- A single action can contain multiple script steps, and
- a later step can use values (including functions) created by an earlier one.
As the Drafts JS API documentation puts it:
Multiple steps in the same action will execute in the same context, so global variables and functions defined in one step will be available to other steps in the same action.
Things, can of course, get accidentally muddled, (when we have taken two steps from different sources, or written them at different times, for example) if the same variable or constant name happens to be used for different purposes, or in ways that are intended to be separate, in each step.
For example, this would trigger an error, which might seem puzzling:
Script step 1
const a = 1789;
Script step 2
const a = 1789;
Resulting error:
SyntaxError: Cannot declare a const variable twice: 'a'.
A simple solution, sometimes called the Javascript module pattern is to make a habit of wrapping your script-step code in bracketing like this:
(() => {
// My Drafts 5 step code goes here
})()
or, equivalently,
(function () {
// My Drafts 5 step code goes here
})()
In other words always write your code, by habit and default, in an βanonymousβ function (function names are optional, and we donβt need one here), which is βimmediately invokedβ. The trailing parentheses after the function body mean that the function is called as soon as it is defined.
Why does this help ?
Because:
- Code inside this bracketing can read and use any global variables defined anywhere outside the bracketing, including in previous script steps, but
- No other code is affected by (or can see) anything which we do inside this bracketing.
The result:
- No unexpected clashes between script steps, and
- anything we do want to share between steps is just placed outside the module brackets.
No unexpected clashes:
This now works fine β no error message:
Script step 1
(() => {
const a = 1789;
})()
Script step 2
(() => {
const a = 1789;
})()
Share just the things we want to share:
If we do want to share anything across steps, we just place it outside the module
bracketing, making it global.
Script step 1
const a = 1789;
(() => {
const x = a; // 1789
})()
Script step 2
(No need to redefine the value a
), and we can use a fresh x
without a clash;
(() => {
const x = a; // 1789
})()