Skip to content
On this page

eventSystem

jsngin implements a custom event system that is more suited for a game type environment.

Types of eventSystems

  • local eventSystem This is the eventSystem on each gameObject. Events specific to this gameObject are triggered on this eventSystem. Eg. collision of this gameObject.

  • global eventSystem This is the global eventSystem and event at fame/root level are triggered on this eventSystem. Eg. LoadCompleteEvent

Scripts for global events

To attach a script to a global event. For the eventName use global_eventName. The export from the script should still be named eventName.

Lifecycle Events

Some basic lifecycle events are defined in the @thejsngin/jsngin implementation. life cycle events


resource event

Is a special type of event and the only event, for which the handler's return value matters. The return value of the resource event is stored as the value for the component inside the gameObject. Incase there are multiple scripts for the resource event, the return values of these scripts must contain a resourceName property, and the final resource is evaluated to be equal to

ts
finalResourceForTheComponent = {
    [res0.resourceName]: res0,
    [res1.resourceName]: res1,
    // ... and so on
}

If any of the return values is a promise then the final resouce is computed after all the promises are fullfilled or rejected.

load event

Is fired on every component to initiate the load procedure. Provides addToLoadTracking function to add weighted resources as promises to the loading queue.

ts
import type { Callback, LoadEvent } from '@thejsngin/jsngin';

const load: Callback<LoadEvent> = (gameInstance, gameObjectInstance, componentHelpers, addToLoadTracking) => {
    let resolve;
    let reject;
    const resourcePromise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
    });

    const resourceWeight = 10;

    addToLoadTracking(resourcePromise, resourceWeight);

    setTimeout(() => {
        if(Math.random() > 0.5){
            resolve();// triggers `loadProgress`
        }else{
            reject();// triggers `loadError`
        }
    }, 5000);
}

export { load };

loadError event

Fired every time a queued resorce fails to load. Provides failLoad which can fail the entire load procedure.

loadProgress event

Fired every time a queued resource loads. Provides failLoad which can fail the entire load procedure.

loadFailed event

Fired if failLoad is called inside loadError or loadProgress. Stops loading and disposes everthing after this is executed.

loadComplete event

Fired if all the queued resource promisses have settled and failLoad was not called.

dispose event

Fired before either the component is removed / gameObject is removed.