Modules
Updated
Scripts do not share variables by default: each Behavior runs in its own scope, so a let score in one script is invisible to every other. That isolation keeps scripts from breaking each other, but a world often needs common data and code: game rules read by many objects, a score several scripts add to, a library downloaded once. This page covers the two ways scripts share with each other: #pragma export and #pragma import between scripts, and named shared instances with Singleton. A library downloaded from a URL with #pragma import(Name="url") has its own page: Dynamic imports.
Before you start
Section titled “Before you start”- Behavior scripts: the sandbox, and why browser globals are not available.
- Directives: how a
#pragmais written. - Lifecycle hooks: when a script loads and when it stops.
Choosing a way to share
Section titled “Choosing a way to share”| You want | Use |
|---|---|
| One script to publish a value or an API that others read | #pragma export and #pragma import(name) |
| A JavaScript library from a CDN | #pragma import(Name="url") |
| One shared object, created by whichever script needs it first | Singleton |
| Messages between scripts, without shared state | Signals: emit, on, once, off. See Events and signals. |
Exports and imports
Section titled “Exports and imports”#pragma export(name) publishes one of the script’s variables under its name. #pragma import(name) binds that published value in another script, as a variable of the same name:
const rules = { gravity: 9.8, lives: 3 };const state = { score: 0 };#pragma export(rules, state)#pragma import(rules, state)#pragma lifecycle(startup)
function startup() { log('lives:', rules.lives); state.score += 10;}- A pragma may list several names. The exported names must be variables the script declares.
- The export is published when the exporting script has loaded, after its top-level code ran.
- The import is bound when the importing script loads, before its top-level code runs. So the exporter must load first: put it earlier in the scene, so the scene creates it first. A Behavior’s
executionIndexorders the frame’s hooks, not loading. - Mistakes fail the script with a message naming the fix, never a silent
undefined:- Two scripts exporting one name. Each name has one exporter at a time; rename one of them.
- Importing a name nobody exported. Check the spelling, and that the exporter loads first.
- Exporting a name that is also a
#defineis an error.
Values are taken once
Section titled “Values are taken once”An import is a value taken when the importer loads. A number or a string is copied: score++ in the exporter is not seen by importers. To share state that changes, export an object and change its properties, as state.score above, or use a Singleton.
How long an export lasts
Section titled “How long an export lasts”An export lasts as long as its script. When the exporting script stops (its entity destroyed or its scene unloaded) the name is freed. A script loaded again exports it again, and importers that load after that get the new value. Importers that loaded before keep the object they were given.
No script can overwrite, delete or clear what others share: the shared names are not a global any script can reach.
Singletons
Section titled “Singletons”Singleton holds named shared instances for the application: one game manager, one score board, one pool. The first script to ask for a name creates the instance, and every other script gets the same object:
#pragma lifecycle(startup)
function startup() { const score = Singleton.get('score', () => ({ points: 0, best: 0 })); score.points += 10; log('points:', Singleton.score.points);}| Call | What it does |
|---|---|
Singleton. |
The instance under key. The first call runs factory() to create it; later calls return it and never run a factory again. |
Singleton. |
The instance, or undefined when there is none. |
Singleton.key |
The instance under key, read-only. Assigning to it throws. |
Singleton. |
Whether an instance exists under key. |
Singleton. |
Remove the instance, calling its dispose() when it has one. Returns whether there was one. |
- Unlike an export, a singleton does not depend on load order: whichever script runs first creates it.
- The key is a non-empty string, and cannot be
get,hasordelete. - Only the script that created an instance can delete it while that script runs. Once the creator has stopped, any script may.
- Instances stay when the script that created them stops, and across scene switches, for the life of the application.
- A factory that asks for its own key while creating it throws.
Examples
Section titled “Examples”1. Shared settings
Section titled “1. Shared settings”One script publishes the settings; any number of scripts read them.
// Put this Behavior entity near the top of the scene, so it loads first.const settings = { enemySpeed: 2.5, pickupValue: 10, difficulty: 'normal',};#pragma export(settings)#pragma import(settings)#pragma lifecycle(update)
function update(dt) { self.parent.position.z += settings.enemySpeed * dt;}How it works:
#pragma export(settings)publishes the object onceSettings.jxhas run its top-level code.#pragma import(settings)binds the same object inEnemy.jxbefore its own top-level code runs.- Because the exporter must load first, its Behavior entity sits earlier in the scene than the importers.
2. An exported API
Section titled “2. An exported API”An export can be an object of functions, so other scripts call into it instead of touching its data.
#pragma lifecycle(startup)
let total = 0;let label = null;
const scoreboard = { add(points) { total += points; if (label) label.setProps({ text: `Score: ${total}` }); }, get total() { return total; },};#pragma export(scoreboard)
function startup() { label = findEntity('Score Label')?.getComponent(UILabelComponent); scoreboard.add(0);}#pragma import(scoreboard)#pragma lifecycle(startup)
function startup() { on('pickup/clicked', (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again scoreboard.add(5); log('Score is now', scoreboard.total); });}One script exports a scoreboard object of functions that updates a UI Label; another imports it and adds points each time a gem is clicked.
Click the gem to score. Drag to orbit the camera, scroll to zoom.
How it works:
scoreboardcloses overtotalandlabel, which stay private toScoreboard.jx.get total()is a getter: importers readscoreboard.totaland always see the current value, unlike an exported number, which would be copied once.Pickup.jxassumes its parent has a Selectable and a Signal Emitter onpickup/clicked.
3. A game manager as a singleton
Section titled “3. A game manager as a singleton”A singleton needs no load order: every level script asks for the same manager, and the first one creates it.
#pragma lifecycle(startup)
function createGame() { const game = { level: 1, coins: 0 }; game.addCoin = () => { game.coins += 1; emit('game/coins', { coins: game.coins }); }; return game;}
function startup() { const game = Singleton.get('game', createGame); log('Level', game.level, '- coins so far:', game.coins);
on('coin/collected', () => game.addCoin()); on('level/complete', () => { game.level += 1; Scenes.load('level-' + game.level); });}How it works:
Singleton.get('game', createGame)runscreateGameonly the first time; every later call, from any script, returns the same object.- The instance survives scene switches, so the coin count carries over from level to level while each level’s own scripts start fresh.
addCoinrefers to the object by its name,game, rather than throughthis: arrow functions keep the code clear, and in a script the Behavior’s entity is alwaysself, neverthis.
Common mistakes
Section titled “Common mistakes”Importing before the exporter has loaded
Section titled “Importing before the exporter has loaded”The importer fails with a message saying no script exported the name. Move the exporting Behavior entity earlier in the scene, or share through a Singleton, which does not depend on load order.
Exporting a number and expecting it to update
Section titled “Exporting a number and expecting it to update”let score = 0;#pragma export(score)on('coin', () => { score += 1; }); // importers keep the 0 they were givenconst score = { value: 0 };#pragma export(score)on('coin', () => { score.value += 1; }); // importers read score.valueTwo scripts exporting the same name
Section titled “Two scripts exporting the same name”Each name has one exporter at a time; the second script fails to start. Give each export a distinct name, such as levelRules and shopRules.
Assigning to a singleton property
Section titled “Assigning to a singleton property”Singleton.score = { points: 0 }; // throws: read-onlyconst score = Singleton.get('score', () => ({ points: 0 }));score.points += 1;