Context

Context

A Context instance is the primary object for this library; it is usually instantiated by calling create. Callbacks are available on this object that define behaviour when invoked with execute.

Inside each of the callbacks, the this keyword can be used to maintain state. After calling execute the state property will hold this state.

Note: The programmer has the option of defining callbacks on the callbacks object "inline" in the create function directly, and/or defining them via "declaration" after create has returned. Declared callbacks will overwrite inline callbacks.

Constructor

new Context(objopt)

Parameters:
Name Type Attributes Default Description
obj object <optional>
{}

The object for destructuring

Properties
Name Type Attributes Default Description
state any <optional>
{}

The initial state of this in callbacks

callbacks object <optional>
{}

Optionally define the callbacks inline

Properties
Name Type Attributes Description
body bodyCallback <optional>

same as body property below

head headTailCallback <optional>

same as head property below

tail headTailCallback <optional>

same as tail property below

error errorCallback <optional>

same as error property below

Properties:
Name Type Description
body bodyCallback

function that does the main work, but which needs code that sets up or prepares before executing, and/or needs code that tears down or completes. doc

head headTailCallback

callback that does the set up or preparation.

tail headTailCallback

callback that does the tear down or post

error errorCallback

block of code that is invoked upon error occurring. By default does nothing. If defined and returns null then the context will "swallow" the error. Accepts one parameter, the Error object error callback doc

execute function

invokes the head (if present), then body, then tail (if present) functions, in that order, even if an error occurs.

state any

holds state, represented by this inside functions body, head, and tail

Source:
Examples
// create a context which has `object` as initial state
const context = ContextManager.create()
context.head = function (param) {
    this.value = param
};
context.body = function (param) {
    Logger.log(this);
}
context.execute('value');  // outputs {value: 'value'}
// same as above, except with callbacks
const context = ContextManager.create({}, {
    head: function (param) {
        this.value = param;
    },
    body: function (param) {
        Logger.log(this);
    }
});
context.execute('value');  // outputs {value: 'value'}
// creates a context where state is an array
const context = ContextManager.create([]);  // send array as first parameter
context.head = function (param) {
    this.push(param - 1)
};
context.body = function (param) {
    this.push(param);
}
context.tail = function (param) {
    this.push(param + 1);
}
context.execute(2);
Logger.log(context.state);  // [1, 2, 3]