Payload.js is a javascript single page application (SPA) driver that allows you to automate and manage REST API requests and render Handlebars templates or raw HTML from the response data. It also allows you to render Handlebars templates with expressions populated by data in memory, and includes a pub/sub, or publish/subscribe, API for managing custom events.
When DOM objects imbued with Payload.js's selectors are activated, a call to Payload.apiRequest() is performed, which involves making an XHR request and/or rendering a template. Payload.js also contains rendered template/response caching and an extensions API as additional means of integration.
- Installation
- Dependencies
- Selectors
- HTML5 API
- Payload.js Initialization Options
- Primary Methods
- Helper Methods
- API Request Handling
- Payload.js Object Properties
Payload.js can be cloned or downloaded directly from GitHub, installed from NPM, or installed from Bower.
$ npm install payloadjs --save$ bower install payloadjs --save- jQuery >= v1.7
- Handlebars runtime - version depends entirely on your compiler version
Note: Handlebars is not required if you choose to only work with raw XHR responses, e.g. HTML returned directly from an API request.
Payload.js automatically binds to HTML elements based on the following selectors:
- Links (activated on click)
- a[data-selector]
- a[data-url]
- button[data-selector]
- button[data-url]
 
- Forms (activated on submit)
- form[data-selector]
- form[data-url]
 
Payload.js selectors can also contain the data-auto-load attribute to cause them to be automatically invoked on page/template load. Selectors are used to invoke API calls and/or render templates when they receive an appropriate trigger event or they are called directly with Payload.apiRequest().
The most useful feature of Payload.js is its intuitive HTML5 API. It can be used out of the box with little to no configuration and interacted with entirely from HTML. This makes Payload.js accessible to the non-javascript-savvy developer.
<button data-url="/api/endpoint"
        data-template="template-name"
        data-selector=".target-selector">
    Button text
</button>| Option | Type | Default | Description | 
|---|---|---|---|
| apiAccessToken | string | '' | Supply an access token for your application and it will be added as the Authorizationrequest header for all XHR requests. | 
| apiAfterRender | function | $.noop | Invoked just after rendering a template. | 
| apiBeforeRender | function | $.noop | Invoked just before rendering a template. | 
| apiCallback | function | $.noop | Called during API request handling before XHR requests (but after loading a template if no XHR request is required). See API Callback Params for more information about the arguments. | 
| apiOnClick | function | function() { return true; } | Invoked on API link activation; if it returns a false value, Payload.js will skip performing an API request. | 
| apiOnSubmit | function | function() { return true; } | Invoked on API form submission; if it returns a false value, Payload.js will skip performing an API request. | 
| apiResponseParent | string | '' | If set, unserialized XHR response objects will use the specified property as the parent key for response data (e.g. if all API responses contain {"response": {}}). | 
| context | objectorstring | 'body' | Payload.js will only monitor events on the given DOM object or selector string. | 
| dataNamespace | string | '' | If set, Payload will look for data-[dataNamespace]-attributes instead ofdata-attributes. This can be used to preventdata-attribute naming conflicts. | 
| debug | boolean | false | If true, outputs useful debugging information to theconsole. | 
| loadingDefault | boolean | true | If true, sets the default behavior for all XHR requests to clear the$targetelement and show theloadingHtmlwithin it. Iffalse, the$targetelement's content will not be cleared until updated by the$apiresponse. This can be overridden for any API request using thedata-loadingattribute. | 
| loadingHtml | string | <small>Loading...</small> | The default HTML to insert into API $targetif theloadingflag for the request istrue. | 
| partials | object | Handlebars.partials | The namespace containing precompiled Handlebars partials. | 
| subscribers | array | [] | List of events and callback functions to pass to Payload.addSubscribersmethod. These subscribers are initialized upon thePayload.deliverycall. | 
| templates | object | Handlebars.templates | The namespace containing precompiled Handlebars templates. | 
| timeout | number | 0 | Timeout value, in milliseconds, before XHR requests are aborted. This can be overridden for any API request using the data-timeoutattribute. If set to0, no timeout will occur. | 
| xhrAlways | function | $.noop | Called after each XHR request, regardless of success/failure. | 
| xhrBeforeSend | function | $.noop | Called before each XHR request. | 
| xhrDone | function | $.noop | Called after each successful XHR request. | 
| xhrFail | function | $.noop | Called after each failed XHR request. | 
- deliver(options)- Used to initialize the initial options to Payload.js and start monitoring the Payload.js context for events; see Payload.js Options.
- apiRequest($origin)- Automatically called when a selector is activated. May also be called explicitly by passing in a jQuery object with the proper data attributes. See API Request Handling for more information about this method.
- triggerAutoLoad($element)- Perform an API request on any DOM nodes containing the attribute- data-auto-load. If- $elementis given, perform an API request on the given jQuery object instead of on the Payload.js- $context.
- publish(eventName, arguments)- Publish a Payload.js. Any arguments given will pass through to the event handlers subscribed to the event named.
- subscribe(eventName, function)- Subscribe to a Payload.js event. When the specified event is published the function provided will be invoked and passed event-specific arguments.
- unsubscribe(eventName, function)- Stop subscribing to a Payload.js event.
- addSubscribers(subscribers)- Subscribe multiple functions to an array of events:- subscribers={events: [], methods: []}.
- clearCache(type, key)- Based on the- type, the cached "response" data will be cleared for the given key. If no- typeis specified all caches are cleared. If a- typeis specified but no- key, then all items within that- typeof cache are cleared.
- merge(options)- Allows you to merge or extend the current Payload.js options with new options via the given object.
- serializeObject($form)- Serializes form data into an object, automatically creating arrays for form fields containing the same name.
- debug(m)- Allows you to pass in a single method as a string with the subsequent parameters being that method's arguments, OR pass in an object containing keys as method names and values as method arguments (single argument or array of multiple arguments).
Once a selector has been activated, Payload.js performs any API calls requested and renders the template specified. Your app can interact with Payload.js via various callback methods and by "subscribing" to API events. Upon completion of rendering a template, Payload.js will call Payload.triggerAutoLoad($target).
When performing an API request Payload.js will also manage showing and hiding loading indicators. If the "data-loading" attribute is set to "true" (or the "loadingDefault" option is true) the "$target" element will be cleared and have the "loadingHtml" inserted. Otherwise Payload.js will look for an element with the attribute data-role set to loading and call jQuery.show() on it.
Note that DOM objects must either perform an API call by having api.url set (see the API Object and HTML attributes) or specifying a template to load.
- Subscribe to events with the beforeRendernamespace to modify any data before the view is rendered.
- Invoke apiCallbackmethod set in Payload.js options (see API Callback Params).
- If no API URL was specified or a cached view was used, publish the API events and trigger auto-load.
- Show any configured loading indicators.
- Perform the XHR.
1. Failures will invoke the xhrFailcallback option. 1. ThexhrAlwayscallback option always gets called on XHR completion. 1. ThexhrDonecallback is invoked upon a successful XHR.
- If a template selector is defined, render the template into the specified location. If api.loadingwas set, the loading element will quickly fade out first. ThexhrDonecallback option is invoked, API events are published, andtriggerAutoLoad($target)is called.
- Cache the XHR response if requested.
When invoking events or invoking callbacks for apiCallback, apiBeforeRender, and apiAfterRender, a params argument is passed to the handler. It contains the following properties:
- $origin- The jQuery object the Payload.js API originated on.
- $target- The jQuery object pointed to by- $origin's- [data-selector]attribute.
- api- The API object described in API Object and HTML Attributes.
If the API call involves making a XHR request the following additional attributes are abilable on the "params" object:
- response- API response
- status- jQuery status result
- jqXHR- jQuery XHR response object
- html- template HTML (undefined until HTML is rendered)
- api- The API object described in API Object and HTML Attributes.
The API object defined below is passed within the API params to the various callback methods. The various options are controlled through HTML data- attributes on the $origin object, which points to a $target object for template rendering.
- href- The- hrefattribute value from- $origin; for reference and for use with an external routing component
- url-- $origin- data-urlor- action(form) attribute; Used as API URL if set
- method-- $origin- data-methodor- methodattribute; HTTP method to use in API call (default:- 'get')
- cacheRequest-- $origin- data-cache-requestattribute; if- trueflag XHR request to be cached
- cacheResponse-- $origin- data-cache-responseattribute; if- trueuse cached response from Payload.js
- type- jQuery XHR request type (default:- 'json')
- selector-- $origin- data-selectorattribute; jQuery selector for the API $target that a template will be loaded into
- template-- $origin "data-template" attribute; name of the Handlebars template to load into the location specified bydata-selector- (overridesdata-partial` if also set)
- partial-- $origin- data-partialattribute; name of the Handlebars partial template to load into the location specified by- data-selector
- events-- $origin- data-publishattribute; space-separated list of events to have published to Payload.js subscribers
- requestData- combination of JSON serialized form data and any JSON-encoded values within $origin- data-formattribute
- templateData- See Template Data below
- loading-- $origin- data-loadingattribute; if "true" (or the- loadingDefaultoption is true) the- $targetelement will be cleared and have the- loadingHtmlfrom Payload.js options inserted during API request handling.
Every Handlebars template always has the following data available:
- app- Any custom application data contained in- Payload.appData
- request-- href,- url,- method, and- cacheKeyfor the API call
- view- A dictionary of all- data-*attributes from- $origin
- options- Current set of options (see Payload.js Options)
- appData- Object for storing arbitrary application data; provided as- appwithin template data
- cache- Object containing- responsecache; available for external component cache