npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

appworks-js

v22.3.2

Published

JavaScript library providing an interface for native bindings provided by AppWorks mobile and desktop clients.

Downloads

104

Readme

appworks.js

What is appworks.js?

appworks.js is a javascript (TypeScript) library for building feature rich, hybrid enterprise apps. The OpenText AppWorks platform provides mobile and desktop clients that support apps that utilize appworks.js.

In a mobile environment the library provides access to on-device technology, and in the desktop environment some features of the underlying host OS (operating system) are exposed.

Supported platforms:

  • mobile
    • iOS
    • Android
  • desktop
    • Windows
    • OSX
    • Linux

A limited number of appworks.js plugins are available in the desktop environment. They are marked in the API Usage and Examples section and are listed for quick reference below:

Update Notes

v22.3.2

Fixed return type issues in Cache, DesktopStorage, OnDeviceStorage.

v22.3.1

Added updateLastModifiedDate(path: string, date: Date, successCallback: (result: boolean) => void, errorCallback?: (result: Error) => void ) to update the last modified date of the specified file path with the supplied Date.

v22.3.0

Now Desktop Clients can use AWComponent to listen for close event using registerAppClose() method in AWComponent.

Only two methods of AWComponent i.e registerAppClose() and closeApp() are available to use for Desktop Clients.

v16.7

Import updates for AWCache, please see AWCache changes for 16.7 within the AWCache section

New first run methods added to AWAppManager

Installation

NPM:

npm install appworks-js --save

Yarn

yarn add appworks-js

Bower:

bower install --save appworks-js
  • You can find the production files in the dist directory.

Auto install:

If you are deploying an app to the gateway, the gateway will automatically add appworks.min.js to the root of your project. If you opt to use the bundled file make sure your script tag looks like this:

<script src="appworks.min.js"></script>

Table of Contents

API Usage and Examples

Plugin

All plugins have the following type definition:

abstract class AWPlugin {
    successHandler: () => void;
    errorHandler: () => void;
    /**
     * Base plugin class. Constructor takes in a success function and error function to be executed upon
     * return from call to native layer
     * @param successHandler - the function to be executed when the native call succeeds. passes an object as arg
     * @param errorHandler - the function to be executed when the native call fails. passes an object as arg.
     */
    constructor(successHandler: any, errorHandler: any) {
        this.successHandler = successHandler;
        this.errorHandler = errorHandler;
    }
}

This means that whenever creating a new Plugin object, you must initialize it with your success and error callbacks. When the call to the native layer succeeds or fails, your handler will get executed. If you require a new callback to be executed, create a new object. Plugin objects extend AWPlugin and are listed below, under the subcategory Plugin.

For example:

var camera = new Appworks.AWCamera(onSuccess, onFail);

function onSuccess(data) {
    console.log(data);
    // do something with data
}

function onFail(err) {
    console.log(err);
}

camera.takePicture();

Note: if you are using angularJS, $scope.$apply() calls will need to be made in your callbacks to ensure that scope variables and the DOM get updated.

AWAuth

* available on desktop

The Auth plugin allows you to seamlessly authenticate against your backend. Useful for refreshing tokens and gaining access rights to make api calls against the gateway.

Methods:
authenticate
authenticate(force?:boolean)

Makes a call against the gateway /auth endpoint. Returns the response to the callback registered upon creation of the instance

  • force: when a truthy value is passed, the client will force a reauthentication by the user.
Example:
var auth = new Appworks.Auth(
    function (data) {
        // got the response, now make backend api calls
        var response = data.data;
        $.ajax({
            method: 'POST',
            url: response.gatewayUrl + '/v1/content/nodes/1234/children',
            headers: { otcsticket: response.addtl.otcsticket },
            data: { foo: bar }
        });
    },
    function (err) {
        // could not complete authentication request
        console.log(err);
    }
);

$('#click-me').click(function () {
    auth.authenticate();
});
getAuthResponse
Marked for depreciation
Use authenticate(boolean?), which will get the auth object if the session is valid, 
else it will refresh the auth object and return the new auth object.
getAuthResponse()

Returns the auth response to the callback registered upon creation of the instance without sending a reauthentication request.

Example:
var auth = new Appworks.Auth(
    function (data) {
        // got the response, now make backend api calls
        var response = data.data;
        $.ajax({
            method: 'POST',
            url: response.gatewayUrl + '/v1/content/nodes/1234/children',
            headers: { otcsticket: response.addtl.otcsticket },
            data: { foo: bar }
        });
    },
    function (err) {
        // could not complete authentication request
        console.log(err);
    }
);

$('#click-me').click(function () {
    auth.getAuthResponse();
});
gateway
gateway(successHandler: any, errorHandler?: any)

Returns the url of the gateway to the successHandler passed in.

online
online(successHandler: any, errorHandler?: any)

Returns a boolean value based on the current network connection, visibility of the gateway and if the user has signed in online (not with offline pin)

Example:
var auth = new Appworks.Auth();
var weAreOnline = false;

$('#click-me').click(function () {
    auth.online(function(status) {
      // Will return true if the device is connected to a network/data, the gateway is responsive to us, and the user is not logged in with the offline pin.
      // Otherwise this will return false.
      weAreOnline = status;
    }, function(error) {
      // Error function calls in the event an error.
      console.log(error);
    });
});
otdsssoticket
otdsssoticket(successHandler: any, errorHandler?: any)

Added so that clients connected to an OAuth2 based gateway are able to specifically request an OTDS SSO Ticket for legacy systems.

If the property "otdsticket" is not in the auth object returned in Auth.authenticate(boolean?), then you are using an OAuth2 setup.

Request an OTDS SSO Ticket by calling this function. It will return the ticket in this functions successHandler, and it will then be in available in the Auth.authenticate(boolean?) response for the life of the OAuth token.

Upon expiry of the OAuth2 session, a new OTDS SSO Ticket must be requested.

Example
function getOtdsSsoTicket() {
  // Create the Auth instance as normal
  var auth = new Appworks.Auth(function(response){}, function(error){});

  // Call otdsssoticket with a success handler and an error handler
  auth.otdsssoticket(function(ticket) {
    // "ticket" is the OTDS SSO Ticket
    console.log("Got Ticket: " + ticket);
  }, function(error) {
    console.log("Error: " + error);
  });
}

Non OAuth2 systems can still use this method, it will simply return the current OTDS SSO Ticket available from Auth.authenticate(boolean?).

AWWebView

* available on desktop The web view plugin allows you to open links via the in-app browser. This is great for giving your app a native feel when opening external links. On Desktop, this plugin allows you to open urls either in the system browser, or a new BrowserWindow.

Note: on Desktop, addEventListener and removeEventListener methods may only be used on BrowserWindow instances opened with the target _self.

Methods:
open
url:string, target?:string, options?: string):InAppBrowser

Opens the in-app browser with the url provided.

  • url: the URL to load
  • target: The target in which to load the URL. Defaults to '_self'
  • options: options for the in-app browser. Defaults to 'location=yes'. The options string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive.
addEventListener
type: string, callback: (event: InAppBrowserEvent) => void

Add an event listener to the browser window opened with open

  • type: the event type
  • callback: a function that will get called when the event with the provided type is emitted
removeEventListener
type: string, callback: (event: InAppBrowserEvent) => void

Remove an event listener from the browser window opened with open

  • type: the event type
  • callback: a function that will get called when the event with the provided type is emitted
show

Show a browser window opened with the open method

close

Close a browser window opened with the open method

executeScript
script: string, callback: (result: any) => void

Execute javascript on the browser window opened with open

  • script: the script to execute. must be a javascript string.
  • callback: a function that will get called when the script is executed

Note: this feature is disabled on Desktop

insertCSS
css: string, callback: (result: any) => void

Insert CSS on the browser window opened with open

  • css: the css to execute. must be a string
  • callback: a function that will get called when the script is executed

Refer to https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/ for more documentation

On Desktop, refer to https://github.com/electron/electron/blob/master/docs/api/browser-window.md#instance-events for a full list of all events available to BrowserWindow instances.

Example:
export class MyWebview {

  alertContent: string;
  ref: any;

  openInExternal() {
    const webview = new AWWebView();
    const url = 'https://www.nytimes.com/';
    this.ref = webview.open(url, '_blank');
    this.alertContent = 'You opened a link!';
    this.ref.addEventListener('close', () => {
      this.alertContent = 'You closed the webview!';
    });
  }

  openInInternal() {
    const webview = new AWWebView();
    const url = 'https://www.nytimes.com/';
    this.ref = webview.open(url, '_self');
    this.alertContent = 'You opened a link!';
    this.ref.addEventListener('close', () => {
        this.alertContent = 'You closed the webview!';
    });
  }

  openMinimized() {
    const webview = new AWWebView();
    const url = 'https://www.nytimes.com/';
    this.ref = webview.open(url, '_self', {show: false});
    this.alertContent = 'You opened a browser window that is "closed"';
  }

  showMinimized() {
    if (this.ref) {
      this.ref.show();
    }
  }

  executeScript() {
    if (this.ref) {
      const script = `alert('You executed javascript inside a browser window!')`;
      this.ref.executeScript(script, () => {
        this.alertContent = 'You executed a script!';
      });
    }
  }

  insertCSS() {
    if (this.ref) {
      const css = `* { color: red !important; }`;
      this.ref.insertCSS(css, () => {
        this.alertContent = 'You inserted CSS';
      });
    }
  }
}

AWAppManager

The AppManager plugin allows you to close the current app webview, get the current app name, version and whether it is the first run.

Methods:
closeActiveApp
closeActiveApp()

Closes the currently active app.

Example:
var appManager = new Appworks.AWAppManager(
    function () {
        // success
    },
    function (err) {
        // could not complete request
        console.log(err);
    }
);

$('#click-me').click(function () {
    appManager.closeActiveApp();
});
getAppName
getAppName()

Gets the name of the current active app.

Example:
var appManager = new Appworks.AWAppManager(
    function (appName) {
        console.log("This apps name is: " + appName);
    },
    function (err) {
        // could not retrieve app name
        console.log(err);
    }
);

$('#click-me').click(function () {
    appManager.getAppName();
});
getAppVersion
getAppVersion()

Get the version of the current app

Example:
function getAppVersion() {
  var appManager = new Appworks.AWAppManager();
    appManager.getAppVersion(function (version) {
      console.log(version);
  }, function(error) {
      console.log(error);
  });
}
isFirstRun
isFirstRun()

Determine whether this particular app is running for the first time. Take this opportunity to display an intro carousel or other welcome dialogs.

Example:
function isFirstRun() {
  var appManager = new Appworks.AWAppManager();
    appManager.isFirstRun(function (isFirstRun) {
      if(isFirstRun) {
        console.log('This is the first run of this app');
        // perform first run methods
      } else {
        console.log('This app has run before');
        // perform normal run methods
      }
  }, function(error) {
      console.log(error);
  });
}
setAppHasRun
setAppHasRun()

Tell the AppWorks container that this apps first run has been handled, so that subsequent runs are not incorrectly marked as first run.

Example:
function setAppHasRun() {
  var appManager = new Appworks.AWAppManager();
    appManager.setAppHasRun(function () {
      console.log('setAppHasRun was successful');
  }, function(error) {
      console.log(error);
  });
}

AWComponent

Open, close, list, check components and listen for app close event

Methods:
open
open(successHandler: any, errorHandler?: any, args?: any[])

Open a component

list
list(successHandler: any, errorHandler?: any, args?: any[])

Return a list of all installed components

check
check(successHandler: any, errorHandler?: any, args?: any[])

Check if a component is installed

close
close(successHandler: any, errorHandler?: any, args?: any[])

Close the current component

registerAppClose
registerAppClose(successHandler: any)

Helps the micro app to register itself to listen for app close event.

closeApp
closeApp()

Used to close the Desktop client after performing operations.

Example:
// javascript code example

var awComponent = new Appworks.Component();
function onClose() {
console.log(`close event from callback 1 is called`);
setTimeout(()=>{
    awComponent.closeApp();
},3000); 
}
awComponent.registerAppClose(onClose);
// TypeScript code example
const onClose = () => {
    console.log('Appwork Closed');
    setTimeout(() => {
     alert("Appwork Closed");
     appWorks.closeApp();
    }, 1000);
}

const onError = (error) => {
    this.notify.error('Appwork', error)
}

const appWorks = new AWComponent(null, onError);

appWorks.registerAppClose(onClose);

Finder

The Finder plugin allows you to browse and open files stored on the device inside of the OpenText Mobile container. Files browsing can be done directly inside of your app. Files can be opened in third party iOS apps installed on the device.

Methods:
open
open(path: string, filename: string)

open a file in another iOS app installed on the device

  • path: the path to the file you would like to open
  • filename: the name of the file you would like to open
openDirect
openDirect(filename: string)

open a file in another iOS app installed on the device

  • filename: the name of the file you would like to open at the application root
share
share(filename: string)

Share a file to an another app such as an email client

  • filename: the filepath of the file you would like to open at the application root
list
list(path: string)

show the contents of a directory within the OpenText Mobile app container

  • path: the name of the directory you would like to see the contents of
Example:
var openFile = function (filename) {
    var finder = new Appworks.Finder(showFile, showFileError),

    function showFile(data) {
        console.log(data);
    }

    function showFileError(err) {
        console.log(err);
    }

    finder.open('/', filename);
};

var listDirectory = function (path) {
    var finder = new Appworks.Finder(showContents, showDirectoryError);

    function showContents(directory) {
        console.log(directory);
        // returns an array containing each item in the directory specified by @path

        // try to open file now
        openFile('/', directory[1].filename);
    }

    function showDirectoryError(err) {
        console.log(err);
    }

    finder.list('/');
};

listDirectory();

FileChooser

The FileChooser plugin allows you to select and upload files from the device file system. Android only.

Methods:
selectAndUpload
selectAndUpload(action: string)

select a file and upload

  • action: the action

AWFileSystem

* available on desktop

The AWFileSystem plugin allows AppWorks Desktop hosted apps to interact with the underlying desktop host. Specifically to make use of the OS file system operations, and also some of the native file browsing dialogs (Windows Explorer, OSX Finder, etc.).

Please note this plugin is only usable in the desktop environment, the plugin methods will throw an error if usage outside of this context is detected. Use of relative paths with this plugin's methods is not advised, and paths beginning with a slash on Windows will assume that they begin at the root drive of the hosts file system. Absolute paths can be retrieved via the AWFileSystem dialog methods, namely showSaveDialog, showDirSelector, and showFileSelector.

Methods:
getPath
    getPath(name: string, successCallback: (result: string), errorCallback?: (result: Error))

Retrieve the full path of a well-known location via a special name.

  • name: an alias for a well-known disk location

A String path value will be passed to the callback if the alias is recognised, else the error callback will be fired.

You can request the following paths by the name:

  • home User's home directory.
  • appData Per-user application data directory, which by default points to:
    • %APPDATA% on Windows
    • $XDG_CONFIG_HOME or ~/.config on Linux
    • ~/Library/Application Support on macOS
  • userData The directory for storing your app's configuration files, which by default it is the appData directory appended with your app's name.
  • temp Temporary directory.
  • desktop The current user's Desktop directory.
  • documents Directory for a user's "My Documents".
  • downloads Directory for a user's downloads.
  • music Directory for a user's music.
  • pictures Directory for a user's pictures.
  • videos Directory for a user's videos.
exists
    exists(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Determine if the path provided refers to an existing file or directory. Relative paths should not be used.

  • path: a file path

A boolean value will be passed to the callback if the path does exist, else the error callback will be fired.

isDir
    isDir(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Determine if the path provided refers to a directory, as opposed to a file. Relative paths should not be used.

  • path: a file path

A boolean value will be passed to the callback if the path does refer to an existing directory, else the error callback will be fired.

createFile
    createFile(path: string, successCallback: (result: boolean), errorCallback?: (result: Error), data?: string, append?: boolean)

Create or append to a file at the provided path. A file extension must be provided (e.g. ../myNewImage.jpg). Any extra directories specified in the path that do not currently exist will be created for you.

If data is supplied it will be written to the file, please ensure the file extension is of suitable format to accept String data. If data is not supplied then a new empty file will be created, the file should not currently exist. Use of relative paths will result in an error being thrown.

  • path: a new file path that has a non empty file extension
  • data: text data to be written to the new file (optional)
  • append: should we append to the file if it already exists or overwrite it? (optional)

A boolean value will be passed to the callback if the file/directory was created, else the error callback will be fired.

readFile
    readFile(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Read the contents of a text based (UTF-8) file into a String and return it.

Use of relative paths will result in an error being thrown.

  • path: path of the file to open

A String value will be passed to the callback if the file at the supplied path could be read, else the error callback will be fired.

createDirectory
    createDirectory(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Create a new directory at the provided path. The provided path may contain a trailing slash (both ../myDir/ and ../myDir are valid). Any extra directories specified in the path that do not currently exist will be created for you. This method does not support overwriting existing directories. Use of relative paths will result in an error being thrown.

  • path: a new directory path that may end with a trailing slash

A boolean value will be passed to the callback if the file/directory was created, else the error callback will be fired.

copy
    open(from: string, to: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Copy a file from one location to another. The supplied source and destination paths must be non-empty and contain file extensions. The source path has to refer to an existing file, and any directories in the 'to' path that do not exist will be created as part of the copy operation. Use of relative paths will result in an error being thrown.

  • from: source file path
  • to: destination file path

A boolean value will be passed to the callback if the file was successfully copied, else the error callback will be fired.

open
    open(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Open a file using the host OS. If the file extension of the existing file is known then the corresponding host application will open, else you will be prompted to choose an application. Relative paths should not be used.

  • path: a file path

A boolean value will be passed to the callback if the OS managed to open the file, else the error callback will be fired.

reveal
    reveal(path: string, successCallback: (result: boolean), errorCallback?: (result: Error))

Open the OS file browser at the supplied file path. Relative paths should not be used.

  • path: a file path

A boolean value will be passed to the callback if the OS managed to open the file browser at the supplied location, else the error callback will be fired. Relative paths should not be used.

updateLastModifiedDate
    updateLastModifiedDate(path: string, date: Date, successCallback: (result: boolean) => void, errorCallback?: (result: Error) => void ): void

Update the last modified date of the file specified in the supplied path Relative paths should not be used.

  • path: a file path
  • date: date using which last modified date need to be updated
getDetails
    getDetails(path: string, successCallback: (result: FileDetails), errorCallback?: (result: Error))

Retrieve the details of a specific file/directory at the supplied path. Relative paths should not be used.

  • path: a file path

A FileDetails object will be passed to the callback if the path exists, else the error callback will be fired.

listDirContents
    listDirContents(path: string, successCallback: (result: FileDetails[]), errorCallback?: (result: Error))

List the contents of the directory at the supplied path. Relative paths should not be used.

  • path: a file path

An array of FileDetails objects will be passed to the callback if the path exists and is a directory, else the error callback will be fired.

showSaveDialog
    showSaveDialog(opts: SaveDialogOptions, successCallback: (result: string), errorCallback?: (result: Error))

Show the OS 'Save As' file browser, only permitting selection of a single file. A new file name is usually entered otherwise we will overwrite the existing file at the provided path (provide the correct permissions are in place)

The full path of the file indicated in the OS file browser will be returned to the callback on pressing the dialog confirmation button.

showDirSelector
    showDirSelector(opts: FileDialogOptions, successCallback: (result: string[]), errorCallback?: (result: Error))

Show the OS file selection browser, only allowing the selection of directories.

The full path to the selected directory will be returned to the callback on pressing the dialog confirmation button.

showFileSelector
    showFileSelector(opts: FileDialogOptions, successCallback: (result: string[]), errorCallback?: (result: Error))

Show the OS file selection browser, allowing the selection of files only. Multiple files can be selected at once as specified in the options.

An array of the selected file paths will be returned to the callback on pressing the dialog confirmation button.

Objects:

These objects are defined as part of the AWFileSystem module.

FileDetails

Basic file details resolved by the host OS.

  • name: file name with extension
  • path: full path to the file
  • isDirectory: is this a directory or file?
  • checksum: MD5 hash checksum of the file (files only)
  • modified: last modified time in millis (since epoch)
FileFilter

A filter that can be applied within a file browser to limit the types of file that are visible

  • name: the name of the filter as it appears in the file browser
  • extensions: an array of file extensions without wildcards or dots (e.g. 'png' is good but '.png' and '.png' are bad) to show all files, use the '' wildcard (no other wildcard is supported)
SaveDialogOptions

Options to configure the 'Save As' dialog.

  • title: custom title for the dialog
  • defaultPath: the path at which to open the dialog
  • buttonLabel: custom label for the confirmation button, when left empty the default label will be used
  • filters: an array of FileFilter objects
FileDialogOptions

Options to configure the file browser dialog

  • defaultPath: the file path at which the dialog should be opened
  • multiSelections: enable multiple file selection
  • filters: an array of FileFilter objects

AWHeaderBar

The AWHeaderBar plugin allows you to hide or show the client header bar, update the text, and/or hide or show a back button.

Methods:
setHeader
setHeader(config: any)

update the header bar with options

  • config: a configuration object with the following parameters
  • title: the title of the header
  • backButtonVisible: boolean flag to hide/show the back button
getHeader
getHeader()

get the current configuration of the header

Example:
var setHeader = function () {
    var header = new Appworks.AWHeaderBar(headerWasSet, failed),

    function headerWasSet(config) {
        // returns an object containing the current header bar configuration
        console.log(config);
        // just to demonstrate a callback
        getHeader();
    }

    function failed(err) {
        console.log(err);
    }

    header.setHeader({
        title: 'My New Title',
        backButtonVisible: true
    });
};

var getHeader = function () {
    var header = new Appworks.AWHeaderBar(gotHeader, failed);

    function gotHeader(header) {
        // returns an object containing the current header bar configuration
        console.log(header);
    }

    function failed(err) {
        console.log(err);
    }

    header.getHeader();
};

// update the header bar
setHeader();
setHeaderButtons
setHeaderButtons(callback: Function, config: any)

Set the header buttons to specified images and indicate if their event handler is custom

  • config: an array of objects. The properties of each object must contains:
  • button: The identifier of the button. You can use the AWHeaderBar.ButtonName enumerator for this.
  • image: The identifier of the image. You can use the AWHeaderBar.ButtonImage enumerator for this.
  • function: custom|default - Indicate to AppWorks whether AppWorks will handle the tap event (default) or your app will (custom)
Example:
var self = this;

function initHeaderButtons() {
    self.header = new Appworks.AWHeaderBar(null, failFn);
    setHeaderButtons();
}

// Tell the client to set the header buttons according to the apps needs
function setHeaderButtons() {
  // Button definitions
  var RightButtonOne = {
      "button": AWHeaderBar.ButtonName.RightOne, // Identifiy the button using an enumerator
      "image": AWHeaderBar.ButtonImage.Dots, // Use an image specified by an enumerator
      "function" : "custom" // Inform the client this will be handled in the app
    };

  var RightButtonTwo = {
      "button": AWHeaderBar.ButtonName.RightTwo,
      "image": AWHeaderBar.ButtonImage.Search,
      "function" : "custom"
    };

  var LeftButtonOne = {
      "button": AWHeaderBar.ButtonName.LeftOne,
      "image": AWHeaderBar.ButtonImage.Back,
      "function" : "custom"
    };

  var LeftButtonTwo = {
      "button": AWHeaderBar.ButtonName.LeftTwo,
      "function" : "default" // Inform the client this button is to be handled by the client. The image will revert to default.
    };

  var buttons = [LeftButtonOne, RightButtonOne, RightButtonTwo];
  header.setHeaderButtons(headerButtonCallback, buttons);
}

// Tell the client to set each button to their default icons and functions
function resetHeaderButtons() {
  var RightButtonOne = {
      "button": header.ButtonName.RightOne,
      "function" : "default" // Inform the client this button is to be handled by the client. The image will revert to default.
    };

  var RightButtonTwo = {
      "button": header.ButtonName.RightTwo,
      "function" : "default" // Inform the client this button is to be handled by the client. The image will revert to default.
    };

  var LeftButtonOne = {
      "button": header.ButtonName.LeftOne,
      "function" : "default" // Inform the client this button is to be handled by the client. The image will revert to default.
    };

  var LeftButtonTwo = {
      "button": header.ButtonName.LeftTwo,
      "function" : "default" // Inform the client this button is to be handled by the client. The image will revert to default.
    };

  var buttons = [LeftButtonOne, LeftButtonTwo, RightButtonOne, RightButtonTwo];
  header.setHeaderButtons(headerButtonCallback, buttons);
}

// Callback function called when a button is tapped
function headerButtonCallback(button){
  if(button == header.ButtonName.RightOne) {
    rightButtonOneFunction();
  }

  if(button == header.ButtonName.RightTwo) {
    rightButtonTwoFunction();
  }

  if(button == header.ButtonName.LeftOne) {
    leftButtonOneFunction();
  }
}

function failFn(err) {
    // called when the header bar fails to set the buttons
    console.log(err);
}

// Execute the function to initialize the header buttons
initHeaderButtons();
maskHeader
maskHeader(shouldMaskHeader: any)
  • shouldMaskHeader: A boolean value, true to mask false to unmask
  • Add an overlay to the native header.
  • The buttons underneath are not usable when when the overlay is visible.
Example:
document.addEventListener("deviceready", onDeviceReady, false);

var self = this;

function onDeviceReady() {
  app();
}

function app() {
    self.header = new Appworks.AWHeaderBar();
}

// Invoke the mask header plugin
// Pass in a boolean (true to mask, false to unmask)
function maskHeader(shouldMaskHeader) {
  header.maskHeader(shouldMaskHeader);
}
ButtonName enumerator
  • ButtonName.LeftOne: The left most button, normally the hamburger menu icon
  • ButtonName.LeftTwo: The second left button, no default use.
  • ButtonName.RightOne: The right most button, normally the app switcher icon in the multi app client
  • ButtonName.RightTwo: The second right button, no default use for apps, but the settings icon on the app library page in the multi app client
ButtonImage enumerator
  • ButtonImage.Back: Same image as the back icon. Can be used here as an alternative.
  • ButtonImage.Settings: A settings cog-wheel icon
  • ButtonImage.None: Hides the button
  • ButtonImage.Dots: Three dots stacked vertically icon
  • ButtonImage.Search: Magnifying glass icon

AWMenu [desktop only]

  • available on Desktop The AWMenu plugin allows you to set and action items in the Desktop native dropdown menu.
Methods:
setMenu
    setMenu(sections: MenuSection[])
  • sections: MenuSection objects to add to native menu

Pass in a number of MenuSection objects to be added to the native menu. Each MenuSection object contains a number of MenuItem objects.

MenuSection
export interface MenuSection {
    /**
     * the title of the section
     */
    subhead: string;
    /**
     * the items to add to this section
     */
    items: MenuItem[];
}
MenuItem
export interface MenuItem {
    /**
     * the title text to use for the menu item
     */
    title: string;
    /**
     * the callback to invoke when the user taps the menu item
     */
    action: any;
    /**
     * is the menu item visible?
     */
    visible: boolean;
    /**
     * does the menu item have a badge? e.g. Notifications (1)
     */
    hasBadge: boolean;
}
Example
addItems() {
    const menu = new AWMenu(null, (err) => {
      console.error(err);
    });
    const menuSections = [
        {
            subhead: 'Breakfast',
            items: [
                 {
                     title: 'Steak & Eggs',
                     action: () => {
                         alert('You chose Steak & Eggs. Please watch your cholesterol levels.');
                     },
                     visible: true,
                     hasBadge: true
                 },
                 {
                     title: 'Donuts',
                     action: () => {
                         alert('You chose Donuts. Yummy, but gym time is required');
                     },
                     visible: true,
                     hasBadge: true
                 },
            ]
        },
        {
            subhead: 'Dinner',
            items: [
                {
                    title: 'Smoked black cod and escarole salad',
                    action: () => {
                        alert('Isn\'t this on the menu at Chez Panisse?');
                    },
                    visible: true,
                    hasBadge: false
                },
                {
                    title: 'Cheeseburger, Fries, and a Beer',
                    action: () => {
                        alert('Why not');
                    },
                    visible: true,
                    hasBadge: true
                }
            ]
        }
    ];
    menu.setMenu(menuSections).then(() => {
      alert(`Successfully added ${menuSections.length} sections to menu`);
    });
  }

AWMobileFileSystem [mobile only]

The AWMobileFileSystem plugin allows you to interact with the file system within the appworks mobile client.

You are able to perform file transfer requests such as upload and download, open and share files, and also copy, move, rename and delete files.

Each method has a shared boolean parameter, indicating whether the file location you are targeting is in the documents directory (shared) or file provider storage directory (non shared).

Shared (true) means to share the file with other apps in the appworks container

Shared (false) means to store privately in your apps file provider storage location. This can still be accessed via the file provider and open in methods.

list

list returns a list of files in a given directory relative to the shared/non shared directory

list(directory: string, shared: boolean, success: any, error: any)
  • directory: the directory relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called returning a list of file objects
  • error: callback called if there is a client side error
File I/O Methods:
exists

exists allows you check check if a file exists at a given directory

exists(source: string, shared: boolean, success: any, error: any)
  • source: the filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file exists
  • error: callback called if the file does not exist
rename

rename allows you rename a file

rename(source: string, destination: string, shared: boolean, success: any, error: any)
  • source: the source filepath relative to the shared/non shared directory
  • destination: the destination filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file was renamed successfully
  • error: callback called if the file was not renamed
copy

copy allows you copy a file

copy(source: string, sourceShared: boolean, destination: string, desintationShared: boolean, success: any, error: any)
  • source: the source filepath relative to the shared/non shared directory
  • source shared: source relative to shared or non shared
  • destination: the destination filepath relative to the shared/non shared directory
  • destination shared: destination relative to shared or non shared
  • success: callback called if the file was copied successfully
  • error: callback called if the file was not copied
move

move allows you move a file

move(source: string, sourceShared: boolean, destination: string, desintationShared: boolean, success: any, error: any)
  • source: the source filepath relative to the shared/non shared directory
  • source shared: source relative to shared or non shared
  • destination: the destination filepath relative to the shared/non shared directory
  • destination shared: destination relative to shared or non shared
  • success: callback called if the file was moved successfully
  • error: callback called if the file was not moved
remove

remove allows you remove/delete a file

remove(source: string, shared: boolean, success: any, error: any)
  • source: the filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file is removed
  • error: callback called if the file is not removed
File Import Methods:
listImports

listImports returns a list of files in your apps import directory

listImports(success: any, error: any)
  • success: callback called returning a list of file objects
  • error: callback called if there is a client side error
moveImport

moveImport allows you move a file from the imports directory to a directory of your choosing

moveImport(source: string, destination: string, desintationShared: boolean, success: any, error: any)
  • source: the source filename in the imports directory
  • destination: the destination filepath relative to the shared/non shared directory
  • destination shared: destination relative to shared or non shared
  • success: callback called if the file was moved successfully
  • error: callback called if the file was not moved
File Open Methods:
open

open allows you open the file in a third party app

open(source: string, shared: boolean, success: any, error: any)
  • source: the filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file opens successfully
  • error: callback called if the file was not opened
share

share allows you open the file in a third party app, much the same as open, but Android handles this slighty different, warranting a second method

share(source: string, shared: boolean, success: any, error: any)
  • source: the filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file opens successfully
  • error: callback called if the file was not opened
quicklook

quicklook allows you open the file in iOS using the QuickLook framework with MS office documents and PDFs supported, on Android, you can only use this with PDFs

quicklook(source: string, shared: boolean, success: any, error: any)
  • source: the filepath relative to the shared/non shared directory
  • shared: source relative to shared or non shared
  • success: callback called if the file opens successfully
  • error: callback called if the file was not opened
File Transfer Methods:
download

download allows you to download a file from a URL to a destination filepath

download(source: string, destination: string, headers: any, shared: boolean, success: any, error: any)
  • source: the URL of the file to be downloaded
  • destination: the destination filepath relative to the shared/non shared directory
  • headers: any additional headers besides the standard auth tokens automatically injected
  • shared: destination relative to shared or non shared
  • success: callback called if the file downloaded successfully
  • error: callback called if the file was not downloaded
upload

upload allows you to upload a file to a URL

upload(source: string, destination: string, fileParameterName: string, formData: any, headers: any, shared: boolean, success: any, error: any)
  • source: the source filepath relative to the shared/non shared directory
  • destination: the destination URL
  • fileParameterName: the file parameter name used to identify the file in the request
  • formData: a json object of the form data to be added to the request
  • headers: any additional headers besides the standard auth tokens automatically injected
  • shared: source relative to shared or non shared
  • success: callback called if the file uploaded successfully
  • error: callback called if the file was not uploaded

AWMenu [mobile only]

The AWMenu features available on Android and iOS

Methods:
showMenu
    showMenu(shouldShowMenu: boolean)
  • shouldShowMenu: Set to true to show the menu, set to false to hide the menu, however it's likely only a true value will ever be needed.

This will open (or close) the native side menu.

AWPage

The AWPage plugin allows you to set the URL of page to an external URL (such as http://www.google.com). This allows the web app to launch a new webView with a specified URL in the current context of the view.

Methods:
setPageUrl
setPageUrl(url: string)

Pass in a URL as a string, starting with http(s):// and a webview will overlay the current webview with that URL. For security reasons no appworks functionality will be available from this URL.

Example:
  var page = new Appworks.AWPage();
  var url = "http://www.opentext.com/"
  var awPage = new Appworks.AWPage();
  page.setPageUrl(url);
openModalAppWebView
openModalAppWebView(url: string, title: string)
  • Open a modal webview of a html file in your app which is appworks enabled with query params such as modal.html?myproperty=myvalue
  • This cannot be an external webpage
  • url: the filename and querystring to be opened
  • title: the title to be displayed in the header
Example:
  var page = new Appworks.AWPage();
  var url = "modal.html" + "?property=demonstration";
  var title = "My Page Title";
  var closeTitle = "Done";
  page.openModalAppWebView(url, title, closeTitle);
setActionButtonCallback
setActionButtonCallback(callback: any)
  • Execute a javascript function in your app when the action button is tapped
  • callback: The callback to run when the action button is tapped.
closeModalAppWebView
closeModalAppWebView()
  • Used by the ModalAppWebView which has just popped open. This allows the modal to close itself.
openModalExternalWebView
openModalExternalWebView(url: string, title: string, closeText: string, options?: object)
  • This will open an external webview which is not appworks enabled. Use case: opening your companies website within the app.
  • url: the web URL to be opened
  • title: the title to be displayed in the header
  • closeText: the title to be displayed on the close button
  • options: (optional) a JSON object with a header property and JSON object value to be applied to the web request
Example:
  var page = new Appworks.AWPage();
  var url = "http://mywebsite.com/mypage";
  var title = "My Web Page";
  var closeTitle = "Dismiss";

  var headers = {};
      headers["myKey"] = "myValue";

  var options = {"headers" : headers};

  page.openModalExternalWebView(url, title, closeTitle, options);

AWLauncher

The AWLauncher plugin provides the URL used to open the client in the event it was opened via a custom URL scheme, with the url appended as the launchUrl parameter, e.g. x-otm://?launchUrl=http%3A%2F%2Fmurdoch.opentext.com%2Fnode%2F200 The launchUrl content must be URL encoded.

If your client and domain are setup to use this functionality, then your client will open when you tap on a corresponding link from another app on your device.

This plugin allows your app to get this URL and also clear it to prevent it from being accessed subsequently.

Methods:
getLaunchURL(successHandler: any, errorHandler: any)
  • successHandler will return the url as a string if one is set
  • errorHandler will return a string if no url is set
clearLaunchURL()
  • No parameters, this will simply set the launch URL to null prevent any further access.
Example:
  self.launcher = new Appworks.AWLauncher();
  
  // Retrieve the launch URL
  launcher.getLaunchURL(function(url) {
    // Success, a launch url is set
    alert(url);
  }, function(error) {
    // Error, no launch url is set
    alert(error);
  });

  // Clears the launch URL
  launcher.clearLaunchURL();

QRReader

The QRReader plugin allows you to scan a QR code using the device camera. You can also scan a barcode.

Methods:
scan
scan()

Opens the device camera to scan a QR code. When the QR code is recognized, it is processed automatically. returns the data encoded by the QR code to the callback initialized upon instance creation.

Example:
var scanQRCode = function () {
    var qrScanner = new Appworks.QRReader(onScan, onScanErr),
        qrScanResult;

    function onScan(data) {
        qrScanResult = data;
    }

    function onScanErr(err) {
        console.log(err);
    }

    qrScanner.scan();
};
barcode
barcode()

Opens the device camera to scan a single barcode or multiple barcodes. The contents of the barcode is returned in a string array. You can provide 4 parameters, multiple, timeout, finishTitle and cancelTitle

Example:
var multiple = true; // If true, scan barcodes until users taps finish. If false, scan a single barcode and finish automatically. (Defaults to false if not provided)
var timeout = 30; // The number of seconds of idle (no barcode scan) before automatically finishing. (defaults to 30 if not provided)
var finishTitle = 'All Done'; // A custom title for the finish button (defaults to "Finished" if not provided)
var cancelTitle = 'End Scanning'; // A custom title for the cancel button (defaults to "Cancel" if not provided)
scanBarcode(multiple, timeout, finishTitle, cancelTitle);

// .....

function scanBarcode(multiple, timeout, finishTitle, cancelTitle) {
  var reader = new Appworks.QRReader(
    function(result) {
      // here, result is a string array, e.g. ['barcode1','barcode2','barcode3']
      console.log(result);
    },
    function(error) {
      // here, error is a string
      console.log(error);
    });

  reader.barcode(multiple, timeout, finishTitle, cancelTitle);
}

Camera

Access the device camera to take photos, or select photos from the device gallery.

Methods:
takePicture
takePicture(options?: any)

use the device camera to take a photo. returns the uri specified by options - default is the native uri to the location on the device.

  • options: a CameraOptions object. See apache cordova
openGallery
openGallery(options?: any)

open the device gallery to select a photo. returns the uri specified by options - default is the native uri to the location on the device.

  • options: a

SecureStorage

The SecureStorage Plugin allows you to store and retrieve files on the device using AES 256-bit encryption.

Methods:
store
store(url: string, filename: string, options?: any)

store a file securely.

  • url: the url of the server to download the file from.
  • filename: the path to the file to be stored. may be a directory structure.
  • options: optional options to pass with your request. currently supports headers.
Example:
var self = this;

function storeFile() {

    var storage = new Appworks.SecureStorage(setFile, errorHandler);
    self.imgSrc = null;
    self.loading = true;

    function setFile(file) {
        self.storedFile = file.nativeURL;
        stopLoading();
    }

    function stopLoading() {
        console.log('AWJS: File downloaded successfully.');
        self.loading = false;
    }

    storage.store('http://thecatapi.com/api/images/get', 'file.jpg');
}
retrieve
retrieve(filename: string, options?: any)
  • filename: the name of the file to be retrieved. may be a directory structure. note this is not the nativeURL, but the same path that was supplied to store().
  • options: optional options to pass with your request.
Example:
var self = this;
function getFile() {
    var storage = new Appworks.SecureStorage(showImage, errorHandler);

    function showImage(file) {
        self.storedFile = file.nativeURL;
        self.showStoredFileAsImage = true;
    }

    storage.retrieve('file.jpg');
};

function errorHandler(err) {
    console.log(err);
}
remove
remove(target: string)
  • target: the name of the file to be removed. may be a directory structure. note this is not the nativeURL, but the same path that was supplied to store().
Example:
function removeFile() {
    var storage = new Appworks.SecureStorage(success, errorHandler);
    storage.remove('file.jpg');
}

function success() {
    alert('success');
}

function errorHandler(err) {
    console.log(err);
}
fileExistsAtPath
fileExistsAtPath(target: string)

check if a file exists

  • target: the name of the file to check for. may be a directory structure. note this is not the nativeURL, but the same path that was supplied to store().
Example:
function fileExists() {
    var storage = new Appworks.SecureStorage(success, errorHandler);
    storage.fileExistsAtPath('file.jpg');
}

function success(doesFileExist) {
    alert(doesFileExist); // true or false
}

function errorHandler(err) {
    console.log(err);
}
onprogress
onprogress=

bind a progress function to be passed progress events while the request is being downloaded when store() is called.

AWFileTransfer

* available on desktop

The File Transfer plugin allows you to upload and download files to and from the device. Additionally, it allows you to download files to a shared container where they may be accessed by third party applications installed on the device.

Methods:
download
download(url: string, target: string, options?: any, shared?: boolean)

download a file from a remote url and store it on the device

  • url: the url of the server to download the file from
  • target: the name of the path including the filename where you would like the file to be stored.
  • options: an optional options object. currently supports headers only.
  • shared: a boolean flag. when set, the file will be downloaded to a shared container where it may be accessed by third party applications

This method passes a FileEntry object to your success callback. See Apache Cordova Documentation for more information.

Example:
var self = this;
function downloadFile () {
    var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

    function showFile(file) {
        console.log(file);
        self.downloadedFile = file.nativeURL;
    }

    fileTransfer.progressHandler(function (progress) {
        console.log(progress);
    });

    fileTransfer.download('http://thecatapi.com/api/images/get', 'file.jpg');
};
upload
upload(source: string, url: string, options?: any, shared: boolean)

upload a file from the device to another location

  • source: the name of the path including the filename where the file is stored
  • url: the url of the server to upload the file to
  • options: an optional options object.
  • shared: a boolean flag. when set, the file will be uploaded from a shared container where it may be accessed by third party applications

This method passes a FileUploadResult object to your success callback. See Apache Cordova Documentation for more information.

Example:
var self = this;
function uploadFile () {
    var fileTransfer = new Appworks.AWFileTransfer(showFile, errorHandler);

    function showFile(file) {
        console.log(file);
        self.uploadedFile = file.nativeURL;
    }

    fileTransfer.upload('file.jpg', 'http://thecatapi.com/api/images/get');
};
progressHandler
progressHandler(callback: (data: any) => void)

define a callback to be executed whenever upload or download progress is made

  • callback: a function to be executed during upload or download. passed a ProgressEvent object.
abort
abort()

abort the current transfer.

AWMedia

The AWMedia plugin provides the ability to record and play back audio files on a device.

var media = new Appworks.AWMedia('path-to-src.mp3', audioEnded, errorHandler, statusChanged);

function audioEnded() {
    console.log('audio ended');
}

function errorHandler(err) {
    console.log(err);
}

function statusChanged(status) {
    console.log(status);
}

media.play();
Methods:
  • getCurrentPosition: Returns the current position within an audio file.
  • getDuration: Returns the duration of an audio file.
  • play: Start or resume playing an audio file.
  • pause: Pause playback of an audio file.
  • release: Releases the underlying operating system's audio resources.
  • seekTo: Moves the position within the audio file.
  • setVolume: Set the volume for audio playback.
  • startRecord: Start recording an audio file.
  • stopRecord: Stop recording an audio file.
  • stop: Stop playing an audio file
Parameters:
  • src: A URI containing the audio content
  • mediaStatus: (Optional) The callback that executes to indicate status changes. (Function)

See the Apache Cordova Github for in depth documentation, device specific quirks, and more.

AWMediaCapture

The AWMediaCapture plugin provides access to the device's audio, image, and video capture capabilities.

Methods:
  • captureImage
  • captureVideo
Objects:
  • Capture
  • CaptureAudioOptions
  • CaptureVideoOptions
  • CaptureCallback
  • CaptureErrorCB
  • ConfigurationData
  • MediaFile
  • MediaFileData
Properties:
  • supportedAudioModes: The audio recording formats supported by the device. (ConfigurationData[])
  • supportedImageModes: The recording image sizes and formats supported by the device. (ConfigurationData[])
  • supportedVideoModes: The recording video resolutions and formats supported by the device. (ConfigurationData[])

See the Apache Cordova Github for in depth documentation, device specific quirks, and more.

AWAccelerometer

The AWAccelerometer plugin provides access to the device's accelerometer. The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation, in three dimensions along the x, y, and z axis.

Methods:
getCurrentAcceleration
getCurrentAcceleration()

Get the current acceleration along the x, y, and z axes.

Example:
// onSuccess Callback
// This method accepts an Acceleration object, which contains the current acceleration data
//
var onSuccess = function(position) {
     alert('Acceleration X: ' + acceleration.x + '\n' +
              'Acceleration Y: ' + acceleration.y + '\n' +
              'Acceleration Z: ' + acceleration.z + '\n' +
              'Timestamp: '      + acceleration.timestamp + '\n');
};

function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

var accelerometer = new Appworks.AWAccelerometer(onSuccess, onError);
accelerometer.getCurrentAcceleration();
watchAcceleration
watchAcceleration(options?: any) => watchId: number

Retrieves the device's current Acceleration at a regular interval, executing the successHandler callback function each time. Specify the interval in milliseconds via the accelerometerOptions object's frequency parameter.

  • options - An object with the following optional keys:
    • period: requested period of calls to successHandler with acceleration data in Milliseconds. (Number) (Default: 10000)

returns a watchId that references the watch acceleration interval function. This value should be used with clearWatch to cancel watching for changes in acceleration.

Example:
function onSuccess(acceleration) {
    alert('Acceleration X: ' + acceleration.x + '\n' +
          'Acceleration Y: ' + acceleration.y + '\n' +
          'Acceleration Z: ' + acceleration.z + '\n' +
          'Timestamp: '      + acceleration.timestamp + '\n');
}

function onError() {
    alert('onError!');
}

var accelerometer = new Appworks.AWAccelerometer(onSuccess, onError);
var watchID = accelerometer.watchAcceleration({ period: 30000 });
clearWatch
clearWatch(watchId: number)

Stop watching for changes to the acceleration referenced by the watchId parameter.

Example:
var accelerometer = new Appworks.AWAccelerometer(onSuccess, onError);

var watchId = accelerometer.watchAcceleration();

// .. later on

accelerometer.clearWatch(watchId);

AWCompass

The AWCompass plugin provides access to the device's compass. The compass is a sensor that detects the direction or heading that the device is pointed, typically from the top of the device. It measures the heading in degrees from 0 to 359.99, where 0 is north.

Methods:
getCurrentHeading
getCurrentHeading()

Get the current compass heading. The compass heading is returned via a CompassHeading object using the successHandler callback function.

Example:
function onSuccess(heading) {
    alert('Heading: ' + heading.magneticHeading);
};

function onError(error) {
    alert('CompassError: ' + error.code);
};

var compass = new Appworks.AWCompass(onSuccess, onError);
compass.getCurrentHeading();
watchHeading
watchAcceleration(options?: any) => watchId: number

Gets the device's current heading at a regular interval. Each time the heading is retrieved, the successHandler callback function is executed.

  • options - An object with the following optional keys: - frequency: How often to retrieve the compass heading in milliseconds. (Number) (Default: 100) - filter: The change in degrees required to initiate a watchHeading success callback. When this value is set, frequency is ignored. (Number)

returns a watchId that references the watch heading interval function. This value should be used with clearWatch to cancel watching for changes in heading.

Example:
function onSuccess(heading) {
    var element = document.getElementById('heading');
    element.innerHTML = 'Heading: ' + heading.magneticHeading;
};

function onError(compassError) {
    alert('Compass error: ' + compassError.code);
};

var options = {
    frequency: 3000
}; // Update every 3 seconds

var compass = new Appworks.AWCompass(onSuccess, onError);
var