Javascript actions

A Spice action’s XML definition defines the action for Espresso, but the Javascript file is where the action’s main logic is stored. Like custom TEA actions, Spice Javascript action files should be stored in the Support/Scripts folder:

For custom user actions

~/Library/Application Support/Espresso/Support/Scripts/

For Sugars


Javascript action syntax

Unless you are using no-frills mode, your Javascript will be run as a module. This means that it will be run within its own namespace and automatically have several objects and methods available to it for easy inclusion of Spice’s utility classes (see: Intro to modules and Global variables).

However, aside from the location of the script file (noted above) there are no syntactical requirements. You can, if you wish, simply toss some commands for Espresso in the script and they will be executed when the action is invoked.

Using a main function

If you wish to be able to have Espresso beep on an error, you must include a main function in your script that will be executed by Spice. Because your script is in a module, you must assign your function (by default named main or act) to the exports object:

exports.main = function(parameter1, parameter2) {
    // Body of your function goes here

The main function must return either true or false; if you return false, Espresso will beep to let the user know there was an error.

Requiring modules

Spice includes numerous modules that make working with Espresso easier. Most Spice modules include Mootools-style classes that you will need to initialize, although some include simple functions or previously initialized class instances.

If you wish to require a module, use the following syntax:

var snippet = require('snippet');

You may then access module classes and other exported variables using dot syntax:

var mySnippet = new snippet.Snippet();

Alternatively, you may directly access exported classes when you require the object:

var Snippet = require('snippet').Snippet;

By requiring a Spice module, you will automatically get Mootools-server loaded, but if you wish to ensure that Mootools is running you can use the global shortcut:'mootools-server');

Examples and further reading

The ExampleSpice.sugar bundled with Spice (or available along with the source) includes a very simple and heavily-commented example action that you can tweak and experiment with if you would like to get jump-started on creating Spice actions.

See Intro to modules and Global variables for further info about how Spice modules work and the objects and methods you are provided in your action module for free.

Clicky Web Analytics