Skip to content
Bemi Faison edited this page Feb 23, 2014 · 6 revisions

Salt API: Table of Contents

Status of this document

STATUS: WORKING DRAFT

This is a draft document that contains incomplete and changing content. Do not use this document as reference material.

Please share any concerns about the content of this document, as a new issue.

Overview

The Salt object is both a class and a namespace.

A Salt instance (or "salt") provides methods to access and manipulate programs.

Static Members

The Salt namespace exposes few static members, for accessing and configuring the Salt library.

::pkg

Summary

Returns information on, or references to, Salt packages.

Syntax

(Implemented in Salt 0.3)

Salt.pkg([name]);
Parameters
  • name A valid package name.

Description

pkg informs and resolves package information for the Salt constructor. The method itself comes from the Panzer library.

Packages are class-delegates that monitor and control a shared, private state-machine - in this case, the "navigation loop" used to traverse program states.

When invoked without a name, the method returns an array of package names, in ascending order of creation.

When invoked with a name, the method returns a new or existing package.

Packages have no impact on existing Salt instances.

Packages & performance

Defining new packages may increase the amount of memory used by Salt, and reduce execution speed. The reason is beyond the scope of this document. In short, it is due to how Panzer uses delegated classes to implement functionality of a Salt instance,.

Unless you know what you are doing, avoid using this method to define new packages in Salt.

Examples

List existing Salt packages
var installedPkgs = Salt.pkg();

console.log(installedPkgs); // ['core']
Define a new Salt package
var myPkg = Salt.pkg('woohoo');
console.log(Salt.pkg()); // ['core', 'woohoo']
Retrieve an existing Salt package
var corePkg = Salt.pkg('core');

.version

Summary

The version of the Salt library.

Syntax

(Implemented in Salt 0.1)

Salt.version;

Description

version is a node-semver parseable string.

Examples

Output the Salt version
console.log(Salt.version); // "1.2.3"

Instance Properties

Salt instances have a few properties to easily access and store data. In all cases, you should avoid overwriting these properties directly.

.args

Summary

This property is the array of navigation arguments.

Syntax

(Implemented in Salt 0.5)

saltObj.args;

Description

.args is an array-property, where you may set indices or a new array of navigation arguments. (The values are passed as arguments to the "on" callback of the destination state.)

This is a managed property that is only available during navigation (via traversal callbacks). When idle, the .args member is removed from the salt instance. If the instance had a .args member prior to traversing, that value is restored when navigation ends.

Examples

Validate navigation arguments
var salt = new Salt({
  _in: function () {
    var args = this.args;

    if (args.length !== 2) {
      args[0] = 'default';
      args[1] = 'args';
    }
  },
  _on: function (str1, str2) {
    console.log('received:', str1, str2);
  }
});

salt.get(1, 'insufficient');
// received: default args
Replace navigation arguments
var salt = new Salt({
  _in: function () {
    this.args = ['No', 'way'];
  },
  _on: function (str1, str2) {
    console.log(str1, str2 + '!');
  }
});

salt.get(1, 'Yes', 'sir');
// No way!

.data

Summary

This property is an arbitrary data store.

Syntax

(Implemented in Salt 0.5)

saltObj.data;

Description

.data is a managed property, where arbitrary data members may be assigned at any time, from any routine.

.data is an immutable instance property, which you may reference anywhere in your logic.

A program state can define a data stack, per member, via the _data tag. Exiting a tagged state restores the previous member value. However, because, the stack copies by reference, object-values will remain mutated.

Examples

Scope initial member value
var salt = new Salt({
  _data: 'foo',
  function () {
    var originalFoo = this.data.foo;
    this.data.foo = 5;
    console.log('foo was "' + originalFoo + '"but is now a', typeof this.data.foo);
  }
});

salt.data.foo = 'bar';

salt.go(1);
// foo was "bar" but is now a number
salt.go(0);

console.log(typeof salt.data.foo); // "string"
Share data outside the navigation loop
var salt = new Salt(function () {
  this.data.name = 'Bob';
});

console.log(salt.data.name); // undefined

salt.go(1);

console.log(salt.data.name); // "Bob"

.pkg

Summary

Exposes the instance prototype chain.

Syntax

(Implemented in Salt 0.1)

saltObj.pkg;

Description

.pkg references the prototype chain of a Salt instance. Each "link" in a Salt instance prototype chain is a Salt package, with a unique identifier. The built-in package identifier is "core", referencing instance members prototyped from the "core" package.

Normal use of a Salt instance does not require use of this member. Developers who need to target specific versions of a given prototype member, can access it via .pkg.

Examples

Invoke prototyped method from the "core" package
var salt = new Salt(function () {
  console.log('got here via go');
});

salt.pkg.core.go(1);
// got here via go

salt.pkg.core.go(1);
// got here via go

console.log(salt.go === salt.pkg.core.go); // true

.state

Summary

This property exposes details about the current state.

Syntax

saltObj.state;
saltObj.state.alias;
saltObj.state.delays;
saltObj.state.depth;
saltObj.state.fwds;
saltObj.state.index;
saltObj.state.name;
saltObj.state.path;
saltObj.state.pinned;
saltObj.state.perms;
saltObj.state.root;
saltObj.state.tails;

(Implemented in Salt 0.5)

(Salt 0.5.3, added ".root")

(Salt 0.5.5, added ".delays", ".fwds", and ".tails")

Description

.state presents static information about the current program state, or the instance's position on the program. These details are compiled at instantiation, and can not be changed. You should avoid using this property as anything but a read-only value.

Below lists the members of this object-property:

  • alias: The token that targets this state in a query. The default value is an empty string, which otherwise comes from _alias.
  • depth: The zero-index depth of the program state.
  • delays: When true, a delay (and possible callback) will be scheduled if this state is traversed.
  • fwds: When true, a waypoint will be scheduled when this state is traversed.
  • index: The zero-index order of the program state.
  • name: The name of the program state.
  • path: The absolute query for this state.
  • pinned: When false, delays in this state will not delay child or parent salts. The default value is true, which otherwise comes from _pins.
  • perms: The permissions setting of the program state. This object-value is determined by the _perms tag and the .perms() method. The perms object has three boolean-members: owner, sub, and world.
  • root When true, the state serves as the local root of relative queries. This object-value is determined by the _root.
  • tails: When true, navigation that completes within the program branch will be routed to another state.

Examples

Report the position of an instance in program
var salt = new Salt({
  _sequence: true,
  foo: function () {
    var state = this.state;
    console.log('On "' + state.name + '", at index', state.index, 'and depth', state.depth);
  },
  bar: {
    _import: '//foo/',
    zee: '//foo/'
  }
});

salt.go(1);
// On "foo", at index 2 and depth 2
// On "bar", at index 3 and depth 2
// On "zee", at index 4 and depth 3

.vars

Summary

This property contains arbitrary, navigation-only members.

Syntax

(Implemented in Salt 0.5)

saltObj.vars;

Description

.vars is an object-property where you may assign arbitrary member values.

This is a managed property that is only available during navigation (via traversal callbacks). When idle, the .vars member is removed from the salt instance. If the instance had a .vars member prior to traversing, that value is restored when navigation ends.

Managing vars members

This property is "reset" when the salt enters the "null" state (at index 0). Until then, for the life of the instance, you should remove remove vars members that you no longer need.

Examples

Capture & retrieve sensitive information
var salt = new Salt({
  secret: {
    ask: function () {
      this.vars.ss = window.prompt('What is your secret?');
    },
    share: function () {
      console.log('Your secret is', this.vars.ss);
    }
  }
});

salt.go('//secret/ask');

console.log(salt.vars); // undefined

salt.go('@next');
// Your social is [text entered at prompt]

Instance Methods

#callbacks

Summary

Returns cached callbacks to program queries.

Syntax

(Implemented in Salt 0.5)

saltObj.callbacks(query [, waypoint, blessed]);
Parameters
  • query A valid state query.
  • waypoint Indicates when the query should be a detour vs. a destination. Default is falsy.
  • blessed Indicates when the callback can ignore permissions. Default is falsy.

Description

callbacks is a convenience method that returns curried calls to either .get() or .go(), with the given query. The value returned (by the returned callback function), is the result of the curried method.

Use .callbacks() to bind program navigation with external events. When given the same parameters, this method returns the same callback function.

The query parameter is a program query, which is resolved when the callback is invoked. The callback will not impact the salt if the query fails.

By default, callback invoke the .get() method. Any additional arguments pass-thru as parameters to the .get() method.

When the waypoint parameter is truthy, the returned callback invokes the .go() method, instead. In this case, additional callback arguments are ignored; .go() does not set navigation arguments. Use this flag when you want to preserve the current navigation route.

Blessed callbacks

A "blessed" callback ignores permission settings - it invokes as "self" (a privileged access level). Unless a salt is pinned, it will navigate to the given state, when directed by a blessed callback.

To create a blessed callback, set the blessed parameter to a truthy value. Doing so, requires explictly setting the waypoint parameter; toi match the default, use a falsy value.

A privileged callback is desirable when you need exceptions to reduced permissions. For instance, there may be part of your program where you want to ignore user events (like "click"), but honor window events (like "focus"). When a state denies "world" access, normal callbacks would do nothing. Here, a blessed callback lets you prioritize binds to certain world events over others.

Dynamic callbacks with local & relative queries

The given query parameter is resolved each time you invoke a returned callback function. Given a relative and local query, a callback can therefore target different states (i.e., dynamically) - based on the current program state. For more information on the types of program queries (absolute, local, and relative), see the navigation appendix.

Examples

Direct salts using simple functions
var
  salt = new Salt(function (str) {
    console.log('Hello', str + '!');
  }),
  greetFn = salt.callbacks(1);

greetFn('Bob');
// Hello Bob!
Manage event listener callbacks
var salt = new Salt({
  _in: function () {
    document.addEventListener('DOMContentLoaded', this.callbacks('app'), false);
    console.log('app will show once page loads');
    this.wait();
  },
  app: {/* ... */},
  cancel: {
    _on: function () {
      console.log('abort app load!');
      this.get('@null');
    }
  },
  _out: function () {
    document.removeEventListener('DOMContentLoaded', this.callbacks('app'), false);
    console.log('cleaned event listeners!');
  }
});

salt.go('//app');
// app will show once page loads

salt.go('//cancel');
// aborted app load!
// cleaned event listeners!
Bind slideshow buttons to relative queries
var salt = new Salt({
  _data: ['next', 'prev', 'stage'],
  _in: function () {
    this.data.stage = document.getElementById('slideshow-stage');
    this.data.next = document.getElementById('next-button');
    this.data.next.addEventListener('click', this.callbacks('@next'), false);
    this.data.prev = document.getElementById('previous-button');
    this.data.prev.addEventListener('click', this.callbacks('@previous'), false);
    console.log('click next and previous buttons to step through slideshow!');
  },
  one: {
    _data: {src: 'path/pix1.jpg'},
    _on: function () {
      this.data.stage.src = this.data.src;
      console.log('showing slide "' + this.data.src + '"');
    }
  },
  two: {
    _data: {src: 'path/pix2.jpg'},
    _import: '//one/'
  },
  three: {
    _data: {src: 'path/pix3.jpg'},
    _import: '//one/'
  },
  /* ... N number of "slides", titles doesn't matter ... */
  _out: function () {
    this.data.next.removeEventListener('click', this.callbacks('@next'), false);
    this.data.prev.removeEventListener('click', this.callbacks('@previous'), false);
  }
});

salt.go('//one');
// click next and previous buttons to step through slideshow!
// showing slide "path/pix1.jpg"
Override permissions with privileged callbacks
var salt = new Salt({
  _data: 'cancel',
  _in: function () {
    this.data.cancel = document.getElementById('emergency-button');
  },
  processing: {
    _in: function () {
      this.data.cancel.addEventListener('click', this.callbacks('abort', 0, 1), false);
    },
    _perms: '!world',
    _on: function () {
      console.log('critical process, only user click can abort me!');
    },
    abort: function () {
      this.go(1);
    },
    _out: function () {
      this.data.cancel.removeEventListener('click', this.callbacks('abort', 0, 1), false);
    }
  }
});

salt.go('//processing');
// critical process, only user click can abort me!
Reuse callbacks with local queries
var
  salt = new Salt({
    forth: {
      _root: true,
      _on: function () {
        console.log('started', this.state.name, 'process!');
      },
      final: function () {
        console.log('skipped to final step in', this.state.path.split('/').slice(-3)[0]);
      }
    },
    be: '//forth/',
    prosper: '//forth/'
  }),
  jumpToEnd = salt.callbacks('/final');

salt.go('//forth');
// started forth process!
jumpToEnd();
// skipped to final step in forth

salt.go('//prosper');
// started prosper process!
jumpToEnd();
// skipped to final step in prosper

#go

Summary

Attempts to schedule or traverse toward the current or given target(s), returning true or false as appropriate.

Syntax

(Implemented in Salt 0.1)

saltObj.go([query1, query2, ..., queryN]);
Parameters
  • queryN A valid state query.

Description

go directs your salt toward a program state, and can add new targets to the navigation queue.

Targets are queries resolved from the current state, and added after the current queue target (if any). If any given query argument fails to resolve, the method exits with false, leaving the queue unchanged. If the first query given resolves to the current navigation target, it is ignored. (This is to avoid targeting the same state twice.)

When a salt is idle or paused, the final queue is pursued immediately - before the method returns. In this case, should the subsequent navigation sequence result in one or more traversal events (i.e., "in", "on", "out", etc.), the method will return true. Otherwise, if no traversal events occur, the method returns false.

When a salt is currently navigating (i.e., "active"), or pinned, the queue is/remains scheduled, and the method returns true.

Permission Aware Execution

go knows when it is invoked by another salt, or outside the Salt framework. As such, permissions may be set which can prevent specific access groups from utilizing this method. If a group is denied permission within a program branch, invoking this method simply returns false.

Examples

Direct your salt towards a program state
var salt = new Salt({
  home: function () {
    console.log('home sweet home!');
  }
});

salt.go('//home');
// home sweet home!
Add a waypoint to the navigation queue
var salt = new Salt({
  _in: function () {
    this.go('setup');
  },
  app: function () {
    console.log('app is ready!');
  },
  setup: function () {
    console.log('inited environment!');
  }
});

salt.go('//app');
// inited environment!
// app is ready!
Add multiple waypoints
var salt = new Salt({
  a: function () {
    console.log('easy as one...');
  },
  b: function () {
    console.log('two...');
  },
  c: function () {
    console.log('three!');
  }
});

salt.go('//a', '//b', '//c');
// easy as one...
// two...
// three!
Continually unpause navigation
var salt = new Salt({
  chat: {
    _sequence: true,
    greet: function () {
      console.log('hello!');
      this.wait();
    },
    inquire: function () {
      console.log('are you there?');
      this.wait();
    },
    quit: function () {
      console.log('I give up!');
    }
  }
});

console.log(salt.go('//chat')); // true
// hello!

console.log(salt.go()); // true
// are you there?

console.log(salt.go()); // true
// I give up!

console.log(salt.go()); // false

#owner

Summary

Return or set the owning salt.

Syntax

(Implemented in Salt 0.5.)

saltObj.owner();
saltObj.owner(saltInst);
saltObj.owner(remove);
Parameters
  • saltInst A Salt instance.
  • remove Boolean false.

Description

owner sets or retrieves the owning salt of an instance. When an owner is active (i.e., navigating it's program), it has "owner" level access to manipulate an owned instance. This method is permission-aware, and returns different results based on the environment.

For more on ownership, see the ownership and collections appendix.

Inspect ownership

To determine whether a salt has an owner, invoke this method with no arguments. The returned value depends on whether or not the salt has an owner, and the calling environment. Below lists the possible return values:

  • When there is no owner this method returns false.
  • When there is an owner, and this method is invoked by program of the owned or owner instance, it returns the owner instance.
  • When there is an owner, and this method is invoked outside the owned or owner instance, it returns true.
Set an owner

You may set a new owner via the instance's program or that of it's existing owner. On success, this method returns the given saltInst argument, otherwise false.

Note: An instance can not be it's own owner.

Remove the owner

You may remove the current owner via the instance or owner programs, by passing false. On success, this method returns true, otherwise false.

Examples

Grant ownership to another salt
var
  master,
  salt = new Salt({
    ad: {
      _perms: '!world',
      _on: function () {
        this.owner(master);
        console.log('showing unstoppable ad!');
      },
      _out: function () {
        console.log('stopped advertisement!');
      }
    }
  });

master = new Salt({
  stop_ad: function () {
    salt.go(1);
  }
});

salt.get('//ad');
// showing unstoppable ad!

console.log(salt.perms()); // false

owner.go('//stop_ad');
// stopped advertisement!

#perms

Summary

Set group permissions.

Syntax

(Implemented in Salt 0.5)

saltObj.perms();
saltObj.perms(access1 [, access2, ..., accessN]);
Parameters
  • accessN A group access setting.

Description

.perms() returns true when the environment is allowed to change permissions, otherwise false.

If you intend to set permissions of a program branch (upon entering), use the _perms tag instead.

Examples

Dynamically deny access
var salt = new Salt({
  question: {
    _on: function () {
      console.log('what is 2 + 2?');
      this.wait();
    },
    answer: {
      _on: function (rsp) {
        if (rsp === 4) {
          this.go('correct');
        } else {
          this.go('incorrect');
        }
      },
      correct: function () {
        console.log('you got it right!');
      },
      incorrect: function () {
        console.log('you were wrong and are now banned from this program!');
        this.perms('!world');
      }
    }
  }
});

salt.go('//question');
// what is 2 + 2?

salt.get('answer', 5);
// you were wrong and are now banned from this program!

console.log(salt.go(0)); // false

#query

Summary

Resolves and returns resolved paths.

Syntax

(Implemented in Salt 0.1)

saltObj.query(query1 [, query2, ..., queryN]);
Parameters
  • queryN A valid program query.

Description

query resolves one or more program queries, based on the current program state and permissions of the calling environment. When given one query, it returns the resolved state path string. When given two or more queries, it returns an array of state path strings. Use this method to determine if a program query will be accepted as a navigation target.

If one or more queries can not be resolved, this method returns false.

Examples

Check program paths navigation
var salt = new Salt({
  some: {
    state: {
      _alias: 'myShortcut'
    }
  }
  hidden: {
    _conceal: true
    visible: {
      _conceal: false
    }
  },
  trap: {
    _perms: '!world',
    _on: function () {
      console.log('all "public" queries will now fail!');
    }
  }
});

console.log(salt.query(0)); // "..//"
console.log(salt.query('@null')); // "..//"

console.log(salt.query(1)); // "//"
console.log(salt.query('@program')); // "//"

console.log(salt.query(-1)); // false

console.log(salt.query('@myShortcut')); // "//some/state/"

console.log(salt.query('//hidden')); // false
console.log(salt.query('//hidden/@child')); // "//hidden/visible/"

salt.go('//trap');
// all "public" queries will now fail!
console.log(salt.query('@myShortcut')); // false

#status

Summary

Returns details about the current navigation sequence.

Syntax

(Implemented in Salt 0.1)

saltObj.status();
saltObj.status().targets;
saltObj.status().trail;
saltObj.status().paused;
saltObj.status().pinned;
saltObj.status().loops;
saltObj.status(key);
Parameters
  • key A key to retrieve from the status object.

Description

status provides insight into an active navigation sequence. Use this method to branch logic within or without a program.

When called with no arguments, this method returns a status object, referencing all status items. When called with a key parameter, the matching status member value is returned, or undefined.

Below lists the status object members (possible values for the key parameter).

  • targets An array of program paths that will be targeted next.
  • trail An array of program paths that have been traversed.
  • paused A boolean that is true when navigation is paused.
  • pinned A boolean that is true when navigation is blocked by another (child) salt.
  • loops The number of times the current phase has repeated during navigation.
Status when navigation is complete

When a salt has completed navigating towards a program state, the status object will appear "empty". That is, the targets and trails arrays will be empty, paused and pinned will be false, and loops will be zero.

Examples

Track number of executions per navigation sequence
var salt = new Salt({
  _on: function () {
    console.log('done with run!');
  },
  run: {
    _data: {count: 3},
    _on: function (cnt) {
      var execCnt = this.status('loops') + 1;
      if (cnt) {
        this.data.count = cnt;
      }
      this.go('@self');
      if (execCnt === this.data.count) {
        this.get('@parent');
      }
      console.log('run #' + execCnt + '!');
    }
  }
});

salt.get('//run', 5);
// run #1!
// run #2!
// run #3!
// run #4!
// run #5!
// done with run!
Observe when a salt is paused
var salt = new Salt({
  _in: function () {
    var status;
    this.wait();
    status = this.status();
    console.log('paused on the', status.phase, 'phase, toward "' + status.targets[0] + '"');
  },
  target: function () {
    console.log('arrived at the', this.state.name, 'state!');
  }
});

salt.go('//target');
// paused on the in phase, toward "//target/"

console.log(salt.status('paused')); // true

salt.go();
// arrived at the program state!

console.log(salt.status('paused')); // false
Observe when a salt is pinned
var
  pinner = new Salt(function () {
    this.wait();
  }),
  salt = new Salt({
    _in: function () {
      var status;
      pinner.go(1);
      status = this.status();
      console.log('pinned on the', status.phase, 'phase, toward "' + status.targets[0] + '"');
    },
    target: function () {
      console.log('arrived at the', this.state.name, 'state!');
    }
  });

salt.go('//target');
// pinned on the in phase, toward "//target/"

console.log(salt.status('pinned')); // true

pinner.go();
// arrived at the program state!

console.log(salt.status('pinned')); // false

#subs

Summary

Manages the sub-instance collection.

Syntax

(Implemented in Salt 0.5)

saltObj.subs();
saltObj.subs(null);
saltObj.subs(criteria);
saltObj.subs(saltInst1 [, saltInst2, ..., saltInstN]);
saltObj.subs(remove, criteria);
saltObj.subs(remove, saltInst1 [, saltInst2, ..., saltInstN]);
Parameters
  • criteria A boolean, number, object, regular-expression, or string.
  • saltInstN A Salt instance.
  • remove The string "remove".
  • null A null reference.

Description

subs lets you retrieve, add, and remove items from the collection salts known as sub-instances. The argument signature determines this method's behavior.

subs is permissions aware. Sub-instances may not be added or removed without permission. If retrieving without permissions, the number of sub-instances is returned, instead of an array of object-references.

For more information on sub-instances, see the ownership and collections appendix.

Retrieving Sub-instances

There are several ways to retrieve sub-instances. The simplest is to invoke subs without arguments. This returns an array of salt instances.

To filter the sub-instances you wish to retrieve, pass in a criteria value. If the program branch has a _capture tag, you can use it's value as your criteria by passing in null.

Add Sub-instances

Add sub-instances to your collection, by passing in any number of salts. When successful, this method returns the number of sub-instances added. If any of the passed in values are not sub-instances, the attempt will fail.

Removal Sub-instances

Remove sub-instances by passing the string "remove", then either criteria or salt instances. On success, this method returns the number of instances removed.

If the second value is a salt instance, all additional arguments must be salt instances, or the removal attempt will fail. If the second argument is a criteria value, no additional arguments may be passed, or the removal attempt will fail.

Examples

Add sub-instances to the collection
var salt = new Salt({
  kids: function () {
    var i = 5;
    while (i--) {
      this.subs(new Salt());
    }
  }
});

salt.go('//kids');

console.log("I've got", that.subs(), "kids to feed!"); // I've got 5 kids to feed!
Retrieve sub-instances using capture criteria
var
  kidPrgm = {},
  salt = new Salt({
    _in: function () {
      this.subs(new Salt());
    },
    specific: {
      _capture: {is: kidPrgm},
      _on: function () {
        new Salt();
        new Salt(kidPrgm);
        new Salt(kidPrgm);
        console.log(this.subs(null).length, 'subs match the branch criteria.');
      }
    },
    total: function () {
      console.log(this.subs().length, 'subs in total');
    }
  });

salt.go('//specific');
// 2 subs match the branch criteria.

salt.go('//total');
// 3 subs in total
Remove all sub-instances
var salt = new Salt({
  _sequence: 1,
  add: function () {
    var i = 5;

    while (i--) {
      this.subs(new Salt());
    }
  },
  remove: function () {
    this.subs('remove', true);
  },
  total: function () {
    console.log(this.subs().length, 'sub-instances left!');
  }
});

salt.go(1);
// 0 sub-instances left!

#get

Summary

Attempts to clear the navigation queue and set navigation arguments, returning true, a value, or false depending on whether navigation completes.

Syntax

(Implemented in Salt 0.1)

saltObj.get(query [, arg1, ..., argN]);
Parameters
  • query A valid state query.
  • argN A navigation argument.

Description

get defines a destination target and arguments, clearing the navigation queue.

The destination target is a query resolved from the current state. If the query fails to resolve, the method exits with false, leaving the existing queue and arguments unchanged.

When a salt is idle or paused, the destination is pursued immediately - before the method returns. In this case, should the subsequent navigation sequence not complete (that is, navigation ends before the queue is empty), the method will return false. If navigation completes, the method returns the return-value from the _on callback of the final state, or true when the return-value is undefined (or there is no _on callback).

When a salt is currently navigating (i.e., "active"), or pinned, the new queue and arguments are set, and the method returns true.

Permission Aware Execution

get knows when it is invoked by another salt, or outside the Salt framework. As such, permissions may be set which can prevent specific access groups from utilizing this method. If a group is denied permission within a program branch, invoking this method simply returns false.

Examples

Direct and pass arguments to a salt
var salt = new Salt({
  sum: function (operand1, operand2) {
    console.log(operand1, '+', operand2, '=', operand1 + operand2);
  }
});

salt.get('//sum', 2, 5);
// 2 + 5 = 7
Redirect navigation
var salt = new Salt({
  bomb: {
    _sequence: true,
    count3: function () {
      console.log('3...');
    },
    count2: function () {
      console.log('2...');
    },
    intercept: function () {
      // pass along first navigation argument
      this.get('../saved', this.args[0]);
    },
    count1: function () {
      console.log('1...');
    },
    boom: function (name) {
      console.log('you killed', name + '!');
    }
  },
  saved: function (name) {
    console.log(name, 'was saved!');
  }
});

salt.get('//bomb', 'Joey');
// 3...
// 2...
// Joey was saved!

#wait

Summary

Returns true when program navigation is stopped or delayed - otherwise, false.

Syntax

(Implemented in Salt 0.1)

saltObj.wait();
saltObj.wait(delay);
saltObj.wait(action, delay [, arg1, ..., argN]);
Parameters
  • delay The number of milliseconds to wait before resuming navigation.
  • action A query to target or function to invoke, after the given delay.
  • argN An argument passed to the action.

Description

wait instructs your salt to stop navigating a program, for an arbitrary period of time. Navigation "stops" after a traversal phase completes (e.g., the callback executes). This method only works when the salt is actively navigating a program - otherwise, it returns false.

Without arguments, the pause is indefinite. That is, navigation will only resume once directed to the current or new target, via #get or #go.

When only passed a delay parameter, this method will resume navigation after the given number of milliseconds (via #go).

When passed an action and delay parameter, the action is executed after the given number of milliseconds. The action may either be a query or callback function, and has "self" group permissions.

The query (action) must resolve to a program state, or the method returns false. Otherwise, the resolved target is passed to #get (when the delay expires), along with any additional arguments.

The callback (action) is scoped to the salt object when invoked, and passed any additional arguments. The callback may make additional wait calls, allowing you to delay completing a traversal phase in perpetuity.

Permission Aware Execution

wait knows when it is invoked by another salt, or outside the Salt framework. As such, permissions may be set which can prevent specific access groups from utilizing this method. If a group is denied permission within a program branch, invoking this method simply returns false.

Examples

Delay Execution
var salt = new Salt(function () {
  this.wait(function (phrase) {
    console.log(phrase + ' Just like setTimeout!');
  }, 100, 'Yay!');
});

salt.go(1);
// Yay! Just like setTimeout!
Delay Navigation
var salt = new Salt({
  _in: function () {
    console.log('wait...');
    this.wait(5);
  },
  goal: {
    _in: function () {
      console.log('for it...');
      this.wait(5);
    },
    _on: function () {
      console.log('GOAL!')
    }
  }
});

salt.go('//goal');
// wait...
// for it...
// GOAL!
Delay Execution and Navigation
var salt = new Salt({
  _in: function () {
    this.wait(function () {
      console.log('hello');
    }, 100);
    console.log('waiting for...');
  },
  _on: function () {
    console.log('world!');
  }
});

salt.go(1);
// waiting for...

// hello
// world!
Redirect after delay
var salt = new Salt({
  quiz: {
    _on: function () {
      this.wait('buzzer', 5000);
      console.log('what color was the white whale?');
    },
    buzzer: function () {
      console.log('Oops! took too long to answer!');
    }
  }
});

salt.go('//quiz');
// what color was the white whale?

// Oops! took too long to answer!
Using wait repeatedly while in a state
var salt = new Salt(function (count) {
  this.wait(function callback() {
    console.log(count-- + '!')
    if (count) {
      this.wait(callback, 1000);
    }
  }, 1000);
});

console.log(salt.status().paused); // false

salt.get('@program', 5);
// 5!

console.log(salt.status().paused); // true

// 4!

// 3!

// 2!

// 1!
Clone this wiki locally