checkpoints

The checkpoints plugin enables saving and restoring player state (playlist, currentTime, playing/paused).
It also allows users to register modules, so that they can run customized logic for saving/restoring their state.

IMPORTANT CAVEAT:
Functions cannot be saved/restored via checkpoints.
You should be mindful of any APIs that take callback functions as arguments - they won’t be restored when calling restore.
Examples of such APIs include decision.add() (with decider option), variables.registerAction() and variables.connect().
In order to make sure your project behaves correctly when restoring a checkpoint, only call these APIs from the onPlayerInit hook.
The onPlayerInit hook is always executed at init, so plugins can retain references to callback functions even if restoring.
Alternatively, you can register your own module, and call the necessary APIs when restoring.

Example

// Save a checkpoint before going into battle
function onBeforeBloodyBattle() {
    player.checkpoints.save();
}

// Restore previous checkpoint if the battle did not go so well
function onGameOver() {
    var checkpointsArr = player.checkpoints.checkpoints;
    var lastCheckpoint = checkpointsArr[checkpointsArr.length - 1];
    if (lastCheckpoint) {
        player.checkpoints.restore(lastCheckpoint);
    }
}

Init Options

options : object

Initialization options for the checkpoints plugin.

options.persistent : boolean
property

If true, will use the storage plugin in order to save/load checkpoints to/from persistent storage.
When the plugin is initialized, if this is set to true, it will try to load checkpoints from a previous viewing session (if exists).

Default: true
See: checkpoints.loaded
Example

// playerOptions.json
{
    "plugins": {
        "checkpoints": {
            "persistent": false
        }
    }
}

Properties

player.checkpoints.allCheckpoints : Array.<checkpointMeta>
propertyreadonly

An array of all saved checkpoints metas.

Example

// Filter saved states
var myCheckpoints = player.checkpoints.allCheckpoints.filter(function(checkpointMeta) {
    checkpointMeta.tags.indexOf('mytag') >= 0;
});

player.checkpoints.checkpoints : Array.<checkpointMeta>
propertyreadonly

An array of checkpoints metas, sorted by player.currentTime.
There are a few important distinctions between allCheckpoints and checkpoints:

  • 1. The checkpoints array contains a subset of allCheckpoints. It excludes checkpoints that were saved with the options.pushToCheckpoints set to false.
  • 2. The checkpoints array is sorted by player.currentTime.
  • 3. Restoring a checkpoint will cause all future checkpoints to be removed from the checkpoints array. Future checkpoints are defined as checkpoints that have a higher player.currentTime value than the restored checkpoint. After the restore operation completes, the restored checkpoint will be the last entry in the checkpoints array (until another checkpoint is saved).

See: register, save, restore
Example

console.log(player.checkpoints.checkpoints.length); // 5
player.checkpoints.restore(player.checkpoints.checkpoints[2])
    .then(function() {
        // After restoring a checkpoint, all future checkpoints have been truncated from array
        console.log(player.checkpoints.checkpoints.length); // 3
    });

player.checkpoints.upcomingCheckpointsTime : Array.<number>
propertyreadonly

An array of upcoming checkpoints time in ascending order.
These are checkpoints that were registered using the register method.
Whenever this array is updated, a checkpoints.upcomingupdated event will be triggered.

See: register, checkpoints.upcomingupdated
Example

function timeUntilNextCheckpoint() {
    // If no upcoming checkpoints are currently known, return NaN
    if (!player.checkpoints.upcomingCheckpointsTime.length) {
        return NaN;
    }

    // Otherwise, return the next checkpoint's time minus the current time
    return player.checkpoints.upcomingCheckpointsTime[0] - player.currentTime;
}

player.checkpoints.isLoaded : boolean
propertyreadonly

Have the checkpoints been loaded from persistent storage?
Once the checkpoints.loaded event triggers, this property will be true.

See: checkpoints.loaded, persistent
Example

function onCheckpointsLoaded() {
    // Once checkpoints were loaded, restore latest checkpoint
    var checkpointsArr = player.checkpoints.checkpoints;
    if (checkpointsArr.length) {
        var lastCheckpoint = checkpointsArr[checkpointsArr.length - 1];
        player.checkpoints.restore(lastCheckpoint);
    }
}

if (!player.checkpoints.isLoaded) {
    player.on('checkpoints.loaded', onCheckpointsLoaded);
} else {
    onCheckpointsLoaded();
}

player.checkpoints.version : string
propertyreadonly

The checkpoints plugin’s version string.

Example

console.log('The checkpoints plugin version is', player.checkpoints.version);

Methods

player.checkpoints.save([options]) ⇒ Promise
method

Save the current state.
A checkpoints.saved event will be triggered once the checkpoint has been successfully saved.

Returns: Promise - A promise that resolves with the checkpoint’s checkpointMeta object once the checkpoints has been successfully saved.
See: restore, allCheckpoints, checkpoints, checkpoints.saving, checkpoints.saved

Param Type Description
[options] object An optional options object.
[options.tags] string | Array.<string> A string or array of strings to tag this checkpoint with. Can later be used to filter/identify checkpoints.
[options.pushToCheckpoints] boolean Default true. If false, the checkpoint will not be pushed into the checkpoints array (but will still be pushed to the allCheckpoints array).

Example

player.checkpoints.save()
    .then(function(checkpointMeta) {
        console.log('Successfully saved checkpoint with id:', checkpointMeta.id);
    });

player.checkpoints.restore(checkpoint, [options]) ⇒ Promise
method

Restore a previously saved checkpoint.
A checkpoints.restored event will be triggered once the checkpoint has been successfully restored.

Returns: Promise - A promise that resolves with checkpoint’s checkpointMeta object once the checkpoint has been successfully restored.
See: save, allCheckpoints, checkpoints, checkpoints.restoring, checkpoints.restored, checkpoints.restorerequiresuseraction

Param Type Description
checkpoint checkpointMeta | string The checkpoint to restore. Either a checkpointMeta object or a string id.
[options] object An optional options object. This object will be forwarded as-is to modules {module:checkpoints~restoreFn} implementations.
[options.autoplay] boolean | undefined If defined, its value will override the checkpoint’s original playing state. Value true will ensure that playback will begin after restoring (if environment supports it), and false ensures that player will be paused after restoring. If no value given (undefined), playback state will be determined according to the state at the time the checkpoint was saved.

Example

// Restore the previous checkpoint
var checkpointsArr = player.checkpoints.checkpoints;
var lastCheckpoint = checkpointsArr[checkpointsArr.length - 1];
if (lastCheckpoint) {
    player.checkpoints.restore(lastCheckpoint)
        .then(function(checkpointMeta) {
            console.log('Successfully restored checkpoint with id:', checkpointMeta.id);
        });
}

player.checkpoints.register(node, time, [options])
method

Register a checkpoint.
Will schedule a save operation that will occur later, during a node’s playback.
Once the checkpoint has been successfully saved, the checkpoint will be pushed to the allCheckpoints and checkpoints arrays and a checkpoints.saved event will be triggered.

See: save, checkpoints.saved

Param Type Description
node string | Node | RegExp | function | Array.<*> The node (or nodes) that will trigger a checkpoint save operation. This value can either be a string (node id), a node object, a RegExp that will match one or more node ids, a function that receives a node object and returns true if it matches, or an array of any of these.
time number The time within the node (in seconds) to trigger the checkpoint save operation. A negative value will mean seconds before end of node.
[options] object An optional options object. This will be passed as the options argument to the checkpoints.save() method.

Example

// When a node whose ID starts with 'node_autosave' is played back,
// a checkpoint will be saved when it gets to 3.25 seconds.
player.checkpoints.register(/^node_autosave/, 3.25, {tags: ['myProjectName']});

player.checkpoints.unregister(node, time)
method

Unregister previously registered checkpoints.

See: register

Param Type Description
node string | Node | RegExp | function | Array.<*> The node (or nodes) to unregister the checkpoint from. This value can either be a string (node id), a node object, a RegExp that will match one or more node ids, a function that receives a node object and returns true if it matches, or an array of any of these.
time number The time within the node (in seconds) to unregister the checkpoint from. A negative value will mean seconds before end of node.

Example

// Cancel saving checkpoints for nodes with IDs
// that begin with 'node_autosave' at 3.25 seconds.
player.checkpoints.unregister(/^node_autosave/, 3.25);

player.checkpoints.registerModule(moduleId, saveFn, restoreFn, [options])
method

Extend the checkpoints by registering a module that will perform some additional logic when save/restore are called.

Param Type Description
moduleId string A unique string ID.
saveFn saveFn A function that returns a serialized state (the returned value will be used as the argument for restoreFn). Note that returned value must be JSON.stringify() safe - it must not contain functions or circular references. If save operation is asynchronous, you can return a Promise that resolves with the serialized state.
restoreFn restoreFn A function that receives the serialized state (value returned from saveFn) and performs any logic to deserialize it. Return a Promise if the restore operation is asynchronous.
[options] object An optional options object.
[options.deps] string | Array.<string> Array of dependencies (module names). This will determine the order in which saveFn and restoreFn functions of different modules are invoked.
[options.preRestoreFn] restoreFn Optional. Similarly to restoreFn, this function receives the serialized state and performs any logic. However, this function will be invoked prior to any of the restoreFn functions, before the core player restores its playlist. Use cases may include adding nodes to the repository which will be needed for a successful restore operation. Return a Promise if the operation is asynchronous.

Events

“checkpoints.loaded”
event

Triggered when checkpoints have been loaded from a persistent storage
(i.e. checkpoints from a previous viewing session are now available on the allCheckpoints and checkpoints arrays).

See: isLoaded, persistent, allCheckpoints, checkpoints
Example

function onCheckpointsLoaded() {
    // Once checkpoints were loaded, restore latest checkpoint
    var checkpointsArr = player.checkpoints.checkpoints;
    if (checkpointsArr.length) {
        var lastCheckpoint = checkpointsArr[checkpointsArr.length - 1];
        player.checkpoints.restore(lastCheckpoint);
    }
}

if (!player.checkpoints.isLoaded) {
    player.on('checkpoints.loaded', onCheckpointsLoaded);
} else {
    onCheckpointsLoaded();
}

“checkpoints.saving”
event

Triggered when a checkpoint save operation has started.

See: save, checkpoints.saved
Example

player.on('checkpoints.saving', function() {
    console.log('Checkpoint save operation has started...');
});

“checkpoints.saved”
event

Triggered when a checkpoint was successfully saved.

See: save, checkpoints.saving

Param Type Description
checkpointMeta checkpointMeta The saved checkpoint metadata object.

Example

player.on('checkpoints.saved', function(checkpointMeta) {
    console.log('Successfully saved checkpoint with id:', checkpointMeta.id);
});

“checkpoints.restoring”
event

Triggered when a checkpoint restore operation has started.

See: restore, checkpoints.restored

Param Type Description
checkpointMeta checkpointMeta The checkpoint metadata object being restored.

Example

player.on('checkpoints.restoring', function(checkpointMeta) {
    console.log('Checkpoint restore operation has started for checkpoint:', checkpointMeta.id);
});

“checkpoints.restored”
event

Triggered when a checkpoint was successfully restored.

See: restore, checkpoints.restoring

Param Type Description
checkpointMeta checkpointMeta The checkpoint metadata object being restored.

Example

player.on('checkpoints.restored', function(checkpointMeta) {
    console.log('Successfully restored checkpoint with id:', checkpointMeta.id);
});

“checkpoints.restorerequiresuseraction”
event

Triggered when a restore operation was initiated, but is pending a user interaction.
This may happen on mobile devices (which require interaction in order to start playback) in cases where player instance has not played before.
The restore promise will not resolve before a user interaction occurs.

See: restore
Example

player.on('checkpoints.restorerequiresuseraction', function() {
    showRestoreButton();
});

// Restore the previous checkpoint
var checkpointsArr = player.checkpoints.checkpoints;
var lastCheckpoint = checkpointsArr[checkpointsArr.length - 1];
if (lastCheckpoint) {
    player.checkpoints.restore(lastCheckpoint)
        .then(function(checkpointMeta) {
            console.log('Successfully restored checkpoint with id:', checkpointMeta.id);
        });
}

“checkpoints.updated”
event

Triggered when the checkpoints array has been updated (i.e. a checkpoint has been saved, restored or array has been truncated).
The checkpoints array may be truncated due to a seek operation or a playlist reset.
Note that since checkpoints array is exposed, it could also be altered by 3rd parties, in which case no event will be triggered.

See: checkpoints
Example

player.on('checkpoints.updated', function() {
    if (player.checkpoints.checkpoints.length === 0) {
        clearCheckpointsUI();
    }
});

“checkpoints.upcomingupdated”
event

Triggered when the upcomingCheckpointsTime array has been updated.

See: upcomingCheckpointsTime
Example

player.on('checkpoints.upcomingupdated', function() {
    if (player.checkpoints.upcomingCheckpointsTime.length) {
        console.log('Next checkpoint will be saved at player time: ', player.checkpoints.upcomingCheckpointsTime);
    } else {
        console.log('No upcoming checkpoints are currently known');
    }
});

Callbacks

checkpointMeta : object

An object containing metadata of a checkpoint.

checkpointMeta.id : string
property

The id of the checkpoint.

checkpointMeta.tags : Array.<string>
property

Array of tags associated with the checkpoint.

checkpointMeta.time : number
property

The player.currentTime property at the time the checkpoint was saved.

checkpointMeta.date : number
property

The number of milliseonds elapsed since 1 January 1970 00:00:00 UTC at the time the checkpoint was saved.
This is the result of calling Date.now().

saveFn ⇒ * | Promise
callback

A function that returns a serialized state (the returned value will be used as the argument for restoreFn).
Note that returned value must be JSON.stringify() safe - it must not contain functions or circular references.
If save operation is asynchronous, you can return a Promise that resolves with the serialized state.

Returns: * | Promise - Serialized state or a promise that resolves with the serialized state.
See: registerModule, restoreFn
Example

function saveFn() {
    return {
        score: window.score
    };
}

restoreFn ⇒ undefined | Promise
callback

A function that receives the serialized state (value returned from saveFn) and performs any logic to deserialize it.

Returns: undefined | Promise - If restore operation is asynchronous, return a promise. Otherwise, no return value is needed.
See: registerModule, saveFn

Param Type Description
serializedState * The value returned from saveFn.
[options] object An options object that was optionally supplied to the restore method.

Example

function restoreFn(serializedState, options) {
    if (serializedState && serializedState.score) {
        scoreDomElement.innerHTML = serializedState.score;
    }
}
Rate this page: X
Tell us more!