Options
All
  • Public
  • Public/Protected
  • All
Menu

Base class to extend. Define states as prototype attributes or inside of the constructor. In the latter case remember to call this.registerAll() afterwards (for every sub constructor).

The Exception state is already provided.

class FooStates extends AsyncMachine {
  Enabled: {}

  Downloading: {
    drop: 'Downloaded'
  }

  Downloaded = {
    drop: 'Downloading'
  }

  constructor(target) {
    super(target)
    this.registerAll()
  }
}

class Foo {
  constructor() {
    this.states = new FooStates(this)
  }

  Downloading_state(states, url) {
       fetch(url, this.states.addByCallack('Downloaded'))
  }

  Downloaded_state(states, local_path) {
       console.log(`Downloaded ${this.url} to ${local_path}`)
  }
}

Type parameters

Hierarchy

Index

Constructors

constructor

  • new AsyncMachine(target?: undefined | __type, register_all?: boolean): AsyncMachine
  • Creates a new instance with only one registered state - Exception.

    When extending the class, you should register your states by using either the registerAll or register methods at the end of every sub constructor.

    see

    AsyncMachine for the usage example.

    Parameters

    • Optional target: undefined | __type

      Target object for the transitions, useful when composing a machine.

    • Default value register_all: boolean = true

      Automatically registers all defined states. Works only in case there no other attributes defined on the prototype.

    Returns AsyncMachine

Properties

Protected clock_

clock_: object

List of current ticks per state.

Type declaration

emit

emit: TEmit & IEmit

Protected internal_fields

internal_fields: string[] = ['states_all','lock_queue','states_active','queue_','lock','last_promise','log_level_','clock_','target','internal_fields','piped','id_','print_exception','transition','log_handlers','postponed_queue']

last_promise

last_promise: Promise<any> | null = null

Promise created by one of the delayed mutation methods:

  • ...ByCallback
  • ...ByListener

Resolved once the callback/listener gets called.

lock

lock: boolean = false

If true, this machine is currently during a transition.

lock_queue

lock_queue: boolean = false

If true, this machine's queue is currently being executed.

log_handlers

log_handlers: TLogHandler[] = []

List of handlers receiving log messeges

Protected log_level_

log_level_: number = 0

on

  • on(event: string, listener: Function, context?: Object): this
  • TODO docs TODO rename TPipeBindings to TPipeBinding TODO copy these to once() and emit()

    Parameters

    • event: string
    • listener: Function
    • Optional context: Object

    Returns this

once

  • once(event: string, listener: Function, context?: Object): this
  • TODO docs TODO extract eventToStateName(name: string): (TStates | States) and loose the type casting

    Parameters

    • event: string
    • listener: Function
    • Optional context: Object

    Returns this

piped

piped: object

Map of piped states and their targets.

Type declaration

Protected postponed_queue

postponed_queue: boolean = false

Queue execution got postponed, because this machine is currently during a transition from another machine's queue.

print_exception

print_exception: boolean = false

If true, an exception will be printed immediately after it's thrown. Automatically turned on with logLevel > 0.

Protected queue_

queue_: IQueueRow[] = []

states_active

states_active: ("Exception" | TStates)[] = []

List of active states.

states_all

states_all: ("Exception" | TStates)[] = []

List of all registered state names

target

target: __type | null = null

Target object for the transitions, useful when composing the states instance.

transition

transition: Transition | null = null

Currently executing transition (if any)

Methods

Exception_state

  • Exception_state(err: Error | TransitionException, target_states: string[], base_states: string[], exception_src_handler: string, async_target_states?: string[]): void
  • All exceptions are caught into this state, including both synchronous and asynchronous ones, coming from async methods and callbacks. You can override it with your own and handle exceptions based on passed state data and the actual state.

    Parameters

    • err: Error | TransitionException

      The exception object.

    • target_states: string[]

      Target states of the transition during which the exception was thrown.

    • base_states: string[]

      Base states in which the transition originated.

    • exception_src_handler: string

      The handler state which thrown the exception.

    • Optional async_target_states: string[]

      Only for delayed mutations like addByCallback, these are states which we're supposed to be activated by the callback.

      Example of a custom exception handler

      states = machine(['A', 'B', 'C'])
      states.Exception_state = function(err, target_states) {
        // Re-adds state 'C' in case of an exception when A is active.
        if (exception_states.some((state) => state == 'C') && this.is('A')) {
          states.add 'C'
        }
      }
      

      Example of a manually thrown exception

      states.A_state = function(states) {
        foo = new SomeAsyncTask()
        foo.start()
        foo.once('error', (error) => {
          this.add('Exception', error, states)
        }
      }
      

    Returns void

add

  • add<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): boolean | null
  • add(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): boolean | null
  • Adds specified states to the currently active ones.

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>

      OPTIONAL. Pass it if you want to execute a transition on an external machine, but using this machine's queue.

    • states: ("Exception" | S)[] | "Exception" | S

      Array of state names or a single state name.

    • Rest ...params: any[]

      Params to be passed to the transition handlers (only the ones belonging to the explicitly requested states, not implied or auto states).

    Returns boolean | null

    Result of the transition. false can mean that either the requested states weren't accepted or that the transition has been aborted by one of the negotiation handlers. null means that the machine is busy and the mutation has been queued.

    Basic usage

    const example = machine(['A', 'B', 'C'])
    example.add 'A'
    example.is() // -> ['A']
    example.add('B')
    example.is() // -> ['B']
    

    State negotiation

    const example = machine(['A', 'B'])
    // reject the transition with a negotiation handler
    example.A_enter = function() {
      return false
    }
    example.add('A' ) // -> false
    

    Adding a state on an external machine

    const m1 = machine(['A', 'B'])
    const m2 = machine(['C', 'D'])
    
    m1.A_enter = function() {
      // this transition will be queued and executed after the current
      // transition is completed
      m1.add(m2, 'C') // -> null
    }
    
  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns boolean | null

addByCallback

  • addByCallback<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • addByCallback(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of add, returning a node-style callback for adding the state. Errors are handled automatically and forwarded to the Exception state.

    After the call, the related promise object is available as the last_promise attribute.

    See add for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    someNodeCallback('foo.com', example.addByCallback('B'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

addByListener

  • addByListener<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • addByListener(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of add, returning a listener for adding the state.

    Errors need to be handled manually by binding the exception state to the 'error' event (or equivalent).

    After the call, the related promise object is available as the last_promise attribute.

    See add for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    emitter = new EventEmitter
    emitter.on('ready', example.addByListener('A'))
    emitter.on('error', example.addByListener('Exception'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

addNext

  • addNext<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): number
  • addNext(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): number
  • Deferred version of add, adding the requested states on the next event loop's tick. Useful if you want to start with a fresh stack trace.

    See add for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    example.add('A')
    example.addNext('B')
    example.is() // -> ['A', 'B']
    

    Type parameters

    • S: string

    Parameters

    Returns number

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns number

any

  • any(...states: ("Exception" | TStates)[]): boolean
  • any(...states: ("Exception" | TStates)[][]): boolean
  • Checks if any of the passed states is active. State can also be an array, then all states from this param has to be active.

    Parameters

    • Rest ...states: ("Exception" | TStates)[]

      State names and/or lists of state names.

    Returns boolean

    states = machine(['A', 'B', 'C'])
    states.add(['A', 'B'])
    
    states.any('A', 'C') // -> true
    states.any(['A', 'C'], 'C') // -> false
    
  • Parameters

    • Rest ...states: ("Exception" | TStates)[][]

    Returns boolean

Protected callListener

  • callListener(listener: Function, context: Object, params: any[]): any
  • Override for EventEmitter method calling a specific listener. Binds to a promis if returned by the listener.

    TODO incorporate into EE, saving one call stack frame

    Parameters

    • listener: Function
    • context: Object
    • params: any[]

    Returns any

catchPromise

  • catchPromise<T>(promise: T, target_states?: ("Exception" | TStates)[]): T
  • Binds the Exception state to the promise error handler. Handy when working with promises.

    See Exception_state.

    Type parameters

    • T

    Parameters

    • promise: T

      The promise to handle

    • Optional target_states: ("Exception" | TStates)[]

      States for which the promise was created (the one that failed).

    Returns T

    The source promise, for piping.

clock

  • Returns the current tick of the passed state.

    State's clock starts with 0 and on each activation gets incremented by 1. Ticks lets you keep control flow's integrity across async listeners, by aborting them once the state changes. Easiest way to get the tick-based abort function is to use getAbort.

    Parameters

    Returns number

    Current tick of the passed state

    Example

    const example = machine(['A', 'B', 'C'])
    example.add('A')
    example.add('A')
    example.clock('A') // -> 1
    example.drop('A')
    example.add('A')
    example.clock('A') // -> 2
    `
    

createChild

  • createChild(): this
  • Creates a prototype child with it's own active states, clock, queue and locks.

    Useful for creating new instances of machines created using the machine factory in an efficient manner.

    Example

    const parent = machine(['A', 'B', 'C'])
    const child = parent.createChild()
    
    child.add('A')
    child.is() // -> ['A']
    parent.is() // -> []
    `
    

    // TODO write a test

    Returns this

diffStates

  • diffStates(states1: ("Exception" | TStates)[], states2: ("Exception" | TStates)[]): ("Exception" | TStates)[]
  • Diffs two state sets and returns the ones present only in the first one.

    Parameters

    • states1: ("Exception" | TStates)[]

      List of source states.

    • states2: ("Exception" | TStates)[]

      List of states to diff against (picking up the non existing ones).

    Returns ("Exception" | TStates)[]

    List of states in states1, but not in states2.

drop

  • drop<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): boolean | null
  • drop(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): boolean | null
  • De-activates specified states if any of them is currently active.

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>

      OPTIONAL. Pass it if you want to execute a transition on an external machine, but using this machine's queue.

    • states: ("Exception" | S)[] | "Exception" | S

      Array of state names or a single state name.

    • Rest ...params: any[]

      Params to be passed to the transition handlers (only the ones belonging to the explicitly requested states, not implied or auto states).

    Returns boolean | null

    Result of the transition. false can mean that either the requested states weren't accepted or that the transition has been aborted by one of the negotiation handlers. null means that the machine is busy and the mutation has been queued.

    Basic usage

    const example = machine(['A', 'B', 'C'])
    states.drop('A')
    states.is() // -> ['A']
    states.drop('B')
    states.is() // -> ['B']
    

    State negotiation

    const example = machine(['A', 'B'])
    // reject the transition with a negotiation handler
    states.A_enter = function() {
      return false
    }
    states.add('A') // -> false
    

    Dropping a state on an external machine

    const m1 = machine(['A', 'B'])
    const m2 = machine(['C', 'D'])
    
    m1.A_enter = function() {
      // this transition will be queued and executed after the current
      // transition is completed
      m1.drop(m2, 'C') // -> null
    }
    
  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns boolean | null

dropByCallback

  • dropByCallback<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • dropByCallback(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of drop, returning a node-style callback for dropping the state. Errors are handled automatically and forwarded to the Exception state.

    After the call, the related promise object is available as the last_promise attribute.

    See drop for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    someNodeCallback('foo.com', states.dropByCallback('B'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

dropByListener

  • dropByListener<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • dropByListener(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of drop, returning a listener for dropping the state.

    Errors need to be handled manually by binding the exception state to the 'error' event (or equivalent).

    After the call, the related promise object is available as the last_promise attribute.

    See drop for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    emitter = new EventEmitter
    emitter.on('ready', example.dropByListener('A'))
    emitter.on('error', example.setByListener('Exception'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

dropNext

  • dropNext<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): number
  • dropNext(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): number
  • Deferred version of drop, dropping the requested states on the next event loop's tick. Useful if you want to start with a fresh stack trace.

    See drop for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    states.add('A')
    states.dropNext('A')
    states.is('A') // -> true
    

    Type parameters

    • S: string

    Parameters

    Returns number

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns number

duringTransition

  • duringTransition(): boolean
  • Indicates if this instance is currently during a transition.

    When a machine is during a transition, all state changes will be queued and executed once the transition and the previously queued state changes are finished. See queue.

    Example

    const example = machine(['A', 'B', 'C'])
    
    example.A_enter = function() {
      this.duringTransition() // -> true
    }
    
    example.A_state = function() {
      this.duringTransition() // -> true
    }
    
    example.add('A')
    `
    

    Returns boolean

from

  • from(): ("Exception" | TStates)[]
  • Returns the list of active states from which the current transition started.

    Requires [[duringTranstion]] to be true or it'll throw.

    Returns ("Exception" | TStates)[]

get

  • Returns state's properties and relations.

    Parameters

    • state: TStates | BaseStates

      State name.

      states = machine(['A', 'B', 'C'])
      states.A = { drop: ['B'] }
      
      states.get('A') // -> { drop: ['B'] }
      

    Returns IState<TStates>

getAbort

  • getAbort(state: TStates | BaseStates, abort?: undefined | function): function
  • Returns an abort function, based on the current clock tick of the passed state. Optionally allows to next an existing abort function.

    The abort function return a boolean true in case the flow for the specific state should be aborted, because:

    • the state has been de-activated (at least once)
    • the nested abort function returns true

    Example

    const example = machine(['A', 'B', 'C'])
    
    example.A_state = function() {
      const abort = this.getAbort('A')
      setTimeout( () => {
        if (abort()) return
        console.log('never reached')
      }, 0)
    }
    
    example.add('A')
    example.drop('A')
    `
    

    TODO support multiple states

    Parameters

    • state: TStates | BaseStates

      Name of the state

    • Optional abort: undefined | function

      Existing abort function (optional)

    Returns function

    A new abort function

      • (): boolean
      • Returns boolean

getMethodContext

  • getMethodContext(name: string): Object | null
  • Returns an object for a given handler.

    Parameters

    • name: string

      Handler's name

    Returns Object | null

Protected getPipeBindings

getRelationsOf

hasStateChanged

  • hasStateChanged(states_before: ("Exception" | TStates)[]): boolean
  • Return true if the current state differs from the states_before.

    Parameters

    • states_before: ("Exception" | TStates)[]

      List of previously active states.

    Returns boolean

id

  • id(id: string): this
  • id(get_normalized: true): string
  • id(): string
  • Managed the ID of a machine.

    Sets or gets and also support returning a normalized version.

    Example

    const example = machine()
    // set
    example.id('a b c')
    // get
    example.id() // -> 'a b c'
    // get normalized
    example.id(true) // -> 'a-b-c'
    

    Parameters

    • id: string

    Returns this

  • Parameters

    • get_normalized: true

    Returns string

  • Returns string

is

  • is(states: "Exception" | TStates | ("Exception" | TStates)[], tick?: undefined | number): boolean
  • is(): ("Exception" | TStates)[]
  • Without any params passed, returns all of the current states.

    When a list of states is provided, returns a boolean if all of them are currently active.

    If only one state is passed, you can assert on a certain tick of that state (see clock).

    Parameters

    • states: "Exception" | TStates | ("Exception" | TStates)[]

      One or more state names.

    • Optional tick: undefined | number

      When checking only one state, additionally asserts the clock value for that state.

      states = machine(['A', 'B'])
      states.add('A')
      states.is('A') // -> true
      states.is(['A']) // -> true
      states.is(['A', 'B']) // -> false
      // assert the tick
      tick = states.clock('A')
      states.drop('A')
      states.add('A')
      states.is('A', tick) // -> false
      

    Returns boolean

  • Returns ("Exception" | TStates)[]

listeners

  • listeners(event: string): Function[]
  • Return a list of assigned event listeners.

    Parameters

    • event: string

    Returns Function[]

log

  • log(msg: string, level?: number): void
  • Push a new message to the log with an optional level (defaults to 1).

    Parameters

    • msg: string
    • Default value level: number = 1

    Returns void

logLevel

  • logLevel(log_level: number | string): this
  • logLevel(): number
  • Enables debug messages sent to the console (or the custom handler).

    There's 4 log levels:

    • 0: logging is off
    • 1: displays only the state changes in a diff format
    • 2: displays all operations which happened along with rejected state changes
    • 3: displays more decision logic
    • 4: displays everything, including all possible handlers

    Example

    const example = machine(['A', 'B', 'C'])
    example.logLevel(1)
    example.add('A')
    // -> [add] state Enabled
    // -> [states] +Enabled
    `
    

    Parameters

    • log_level: number | string

    Returns this

  • Returns number

not

  • not(states: "Exception" | TStates | ("Exception" | TStates)[]): boolean
  • Returns true in case of all of the passed states aren't active.

    Example:

    const example = machine(['A', 'B', 'C', 'D'])
    example.add(['A', 'B'])
    
    // not(A) and not(C)
    example.not(['A', 'C']) // -> false
    // not(C) and not(D)
    example.not(['C', 'D']) // -> true
    

    Parameters

    • states: "Exception" | TStates | ("Exception" | TStates)[]

    Returns boolean

parseStates

  • parseStates(states: "Exception" | TStates | ("Exception" | TStates)[]): ("Exception" | TStates)[]
  • Parse state names, check if they exist and always return an array. Throws in of an error.

    Parameters

    • states: "Exception" | TStates | ("Exception" | TStates)[]

      State names to check

    Returns ("Exception" | TStates)[]

    An array of valid state names.

pipe

  • Pipes (forwards) a state to another machine.

    Type parameters

    • S: string

    Parameters

    • state: "Exception" | TStates | ("Exception" | TStates)[]

      Name of the state to pipe.

    • machine: AsyncMachine<S, IBind, IEmit>

      Target machine to which the state should be forwarded to.

    • Optional target_state: S

      If the target state name should be different, this is that name. Applicable if only one state is being piped.

    • Optional flags: PipeFlags

      Different modes of piping. See PipeFlags.

      Piping without negotiation

      const m1 = machine(['A', 'B', 'C'])
      const m2 = machine(['A', 'B', 'C'])
      m1.pipe('A', m2)
      m1.add('A')
      m2.is('A') // -> true
      

      Piping with negotiation

      import { PipeFlags } from 'asyncmachine'
      const m1 = machine(['A', 'B', 'C'])
      const m2 = machine(['A', 'B', 'C'])
      m2.A_enter = function() {
        return false
      }
      m1.pipe('A', m2, null, PipeFlags.NEGOTIATION)
      m1.add('A')
      m2.is('A') // -> false
      

    Returns void

pipeAll

  • Pipes all the states from this machine to the target. Doesn't pipe the Exception state.

    The exception state is never piped.

    Parameters

    Returns void

Protected pipeBind

  • pipeBind<S>(states: "Exception" | TStates | ("Exception" | TStates)[], machine: AsyncMachine<S, IBind, IEmit>, requested_state?: S | null, flags?: PipeFlags): void

pipeRemove

  • Removes an existing pipe. All params are optional.

    Parameters

    • Optional states: "Exception" | TStates | ("Exception" | TStates)[]

      Source states. Empty means any state.

    • Optional machine: AsyncMachine<any, IBind, IEmit>

      Target machine. Empty means any machine.

    • Optional flags: PipeFlags

      Pipe flags. Empty means any flags.

      TODO optimise, if needed

    Returns void

pipeRemoveBinding

  • pipeRemoveBinding(): void
  • TODO should remove a binding returned by pipe() and pipeAll() methods

    Returns void

queue

register

  • register(...states: ("Exception" | TStates)[]): void
  • Register passed state names. State properties should be already defined.

    Parameters

    • Rest ...states: ("Exception" | TStates)[]

      State names.

    Returns void

    const example = machine()
    example.Enabled = {}
    example.Disposed = { drop: ['Enabled'] }
    
    states.register('Enabled', 'Disposed')
    
    states.add('Enabled')
    states.is() // -> 'Enabled'
    

registerAll

  • registerAll(): void
  • Registers all defined states. Use it only if you don't define any other attributes on the object (or it's prototype). If you do, register the states manually with the register method. There's also a shorthand for this method as AsyncMachine.constructor's param.

    class States extends AsyncMachine {
      constructor() {
        this.A = {}
        this.B = {}
    
        this.registerAll()
        console.log(this.states_all) // -> ['Exception', 'A', 'B']
      }
    }
    

    Returns void

removeAllListeners

  • removeAllListeners(event: string): this

removeListener

  • removeListener(event: string, fn: Function, once?: boolean): this
  • Remove event listeners.

    Parameters

    • event: string
    • fn: Function
    • Default value once: boolean = false

    Returns this

set

  • set<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): boolean | null
  • set(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): boolean | null
  • Activates only the specified states and de-activates all the other ones which are currently active.

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>

      OPTIONAL. Pass it if you want to execute a transition on an external machine, but using this machine's queue.

    • states: ("Exception" | S)[] | "Exception" | S

      Array of state names or a single state name.

    • Rest ...params: any[]

      Params to be passed to the transition handlers (only the ones belonging to the explicitly requested states, not implied or auto states).

    Returns boolean | null

    Result of the transition. false can mean that either the requested states weren't accepted or that the transition has been aborted by one of the negotiation handlers. null means that the machine is busy and the mutation has been queued.

    Basic usage

    const example = machine(['A', 'B', 'C'])
    example.set('A') // -> true
    example.is() // -> ['A']
    example.set('B') // -> true
    example.is() // -> ['B']
    

    State negotiation

    const example = machine(['A', 'B'])
    // reject the transition with a negotiation handler
    example.A_enter = function() {
      return false
    }
    example.add('A') // -> false
    

    Activating a state on an external machine

    const m1 = machine(['A', 'B'])
    const m2 = machine(['C', 'D'])
    
    m1.A_enter = function() {
      // this transition will be queued and executed after the current
      // transition is completed
      m1.add(m2, 'C') // -> null
    }
    
  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns boolean | null

setActiveStates_

  • setActiveStates_(explicite_states: ("Exception" | TStates)[], target: ("Exception" | TStates)[]): ("Exception" | TStates)[]
  • Sets the new active states incrementing the counters.

    Parameters

    • explicite_states: ("Exception" | TStates)[]
    • target: ("Exception" | TStates)[]

    Returns ("Exception" | TStates)[]

    An array of previously active states.

setByCallback

  • setByCallback<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • setByCallback(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of set, returning a node-style callback for setting the state. Errors are handled automatically and forwarded to the Exception state.

    After the call, the related promise object is available as the last_promise attribute.

    See set for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    setTimeout(example.setByCallback('B'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (err?: any, ...params: any[]): void
      • Parameters

        • Optional err: any
        • Rest ...params: any[]

        Returns void

setByListener

  • setByListener<S>(target: AsyncMachine<S, IBind, IEmit>, states?: ("Exception" | TStates)[] | "Exception" | TStates, ...params: any[]): function
  • setByListener(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): function
  • Deferred version of set, returning a listener for setting the state.

    Errors need to be handled manually by binding the exception state to the 'error' event (or equivalent).

    After the call, the related promise object is available as the last_promise attribute.

    See set for the params description.

    Example

    const example = machine(['A', 'B', 'C'])
    emitter = new EventEmitter
    emitter.on('ready', states.setByListener('A'))
    emitter.on('error', states.addByListener('Exception'))
    

    Type parameters

    • S: string

    Parameters

    • target: AsyncMachine<S, IBind, IEmit>
    • Optional states: ("Exception" | TStates)[] | "Exception" | TStates
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns function

      • (...params: any[]): void
      • Parameters

        • Rest ...params: any[]

        Returns void

setImmediate

  • setImmediate(fn: Function, ...params: any[]): any

setNext

  • setNext<S>(target: AsyncMachine<S, IBind, IEmit>, states: ("Exception" | S)[] | "Exception" | S, ...params: any[]): number
  • setNext(target: ("Exception" | TStates)[] | "Exception" | TStates, states?: any, ...params: any[]): number
  • Deferred version of set, setting the requested states on the next event loop's tick. Useful if you want to start with a fresh stack trace.

    See set for the params description.

    Example

    states = machine(['A', 'B', 'C'])
    states.set('A')
    states.setNext('B')
    states.is() // -> ['A']
    

    Type parameters

    • S: string

    Parameters

    Returns number

  • Parameters

    • target: ("Exception" | TStates)[] | "Exception" | TStates
    • Optional states: any
    • Rest ...params: any[]

    Returns number

setTarget

  • setTarget(target: __type): this
  • Sets the target for the transition handlers. Useful to keep all your methods in in one class while the states class is composed as an attribute of the target object. There's also a shorthand for this method as a AsyncMachine.constructor's param.

    Parameters

    • target: __type

      Target object.

      class Foo {
        constructor() {
          this.states = machine(['A', 'B', 'C'])
          this.states.setTarget(this)
          this.states.add('A')
        }
      
        A_state() {
          console.log('State A set')
        }
      }
      

    Returns this

states

  • states(): object
  • Returns the JSON structure of states along with their relations.

    Returns object

    JSON version of the current machine. Valid input for the machine factory.

statesToString

  • statesToString(include_inactive?: boolean): string
  • Returns a string representation of the machine (name and the list of states), optionally including the in-active states.

    Parameters

    • Default value include_inactive: boolean = false

    Returns string

to

  • to(): ("Exception" | TStates)[]
  • Returns the list of target states which are about to be active after the transition finishes.

    Requires [[duringTranstion]] to be true or it'll throw.

    Returns ("Exception" | TStates)[]

toString

  • toString(): string

unregister

  • unregister(name: string): void
  • TODO desc TODO sample TODO test

    Parameters

    • name: string

    Returns void

when

  • when(states: "Exception" | TStates | ("Exception" | TStates)[], abort?: TAbortFunction): Promise<null>
  • Resolves the returned promise when all of the passed states are active (at the same time). Accepts an optional abort function.

    Example

    const example = machine(['A', 'B', 'C'])
    example.when(['A', 'B']).then( () => {
      console.log('A, B')
    }
    
    example.add('A')
    example.add('B') // prints 'A, B'
    

    TODO support push cancellation

    Parameters

    • states: "Exception" | TStates | ("Exception" | TStates)[]

      List of state names

    • Optional abort: TAbortFunction

      Existing abort function (optional)

    Returns Promise<null>

    Promise resolved once all states are set simultaneously.

whenNot

  • whenNot(states: "Exception" | TStates | ("Exception" | TStates)[], abort?: TAbortFunction): Promise<null>
  • Resolves the returned promise when all of the passed states are NOT active (at the same time). Accepts an optional abort function.

    Example

    const example = machine(['A', 'B', 'C'])
    example.when(['A', 'B']).then( () => {
      console.log('A, B')
    }
    
    example.add('A')
    example.add('B') // prints 'A, B'
    

    TODO support push cancellation TODO merge with when(active, inactive)

    Parameters

    • states: "Exception" | TStates | ("Exception" | TStates)[]

      List of state names

    • Optional abort: TAbortFunction

      Existing abort function (optional)

    Returns Promise<null>

    Promise resolved once all states are set simultaneously.

Object literals

Exception

Exception: object

Exception state's properties. See Exception_state final transition handler.

type

{IState}

multi

multi: true = true

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc