Package Exports
- payloadjs
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (payloadjs) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Payload.js
Payload.js is a javascript single page application (SPA) driver that creates a global Payload object to automate API requests and render Handlebars templates or raw HTML data within the DOM. Payload.js's behaviors are initialized by calling Payload.deliver() with a default object of options, and are further controlled by setting various HTML data- attributes on DOM objects.
When DOM objects imbued with Payload.js's selectors are activated, a call to Payload.apiRequest() is performed, which involves making a XHR request and/or rendering a template. Payload.js also contains template/response caching and an event system as additional means of integration.
Table of Contents
- Installation
- Dependencies
- Selectors
- HTML5 API
- Payload.js Initialization Options
- Primary Methods
- Helper Methods
- API Request Handling
- Payload.js Object Properties
Installation
Payload.js can be downloaded directly from GitHub, installed from NPM, or installed from Bower.
Install from NPM
$ npm install payloadjs --saveInstall from Bower
$ bower install payloadjs --saveDependencies
- 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.
Selectors
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 user or trigger event.
HTML5 API
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 web developer.
<a href="/history-url"
data-url="/api/endpoint"
data-template="template-name"
data-selector=".dom-selector">My link text</a>Payload.js Initialization Options
| Option | Type | Default | Description |
|---|---|---|---|
apiAccessToken |
string |
'' |
Supply an access token for your application and it will be added as the Authorization request 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 |
object or string |
'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 of data- attributes. This can be used to prevent data- attribute naming conflicts. |
debug |
boolean |
false |
If true, outputs useful debugging information to the console. |
loadingDefault |
boolean |
true |
If true, sets the default behavior for all XHR requests to clear the $target element and show the loadingHtml within it. If false, the $target element's content will not be cleared until updated by the $api response. This can be overridden for any API request using the data-loading attribute. |
loadingHtml |
string |
<small>Loading...</small> |
The default HTML to insert into API $target if the loading flag for the request is true. |
partials |
object |
Handlebars.partials |
The namespace containing precompiled Handlebars partials. |
subscribers |
array |
[] |
List of events and callback functions to pass to Payload.addSubscribers method. These subscribers are initialized upon the Payload.delivery call. |
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-timeout attribute. If set to 0, 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. |
Primary Methods
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 call on any DOM nodes containing the attributedata-auto-loadset totrue. If$elementis given, triggerauto-loadon the parameter 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 thetype, the cached "response" data will be cleared for the given key. If notypeis specified all caches are cleared. If atypeis specified but nokey, then all items within thattypeof cache are cleared.
Helper Methods
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).
API Request Handling
Once a selector has been activated, Payload.js perform 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.
API Request Flow
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.
- Publish events with
prenamespace to allow any preparation work to happen. - 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 request.
1. Failures will invoke the
xhrFailcallback option. 1. ThexhrAlwayscallback option always gets called on XHR request completion. - 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.
API Callback Params
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 responsestatus- jQuery status resultjqXHR- jQuery XHR response objecthtml- template HTML (undefined until HTML is rendered)api- The API object described in API Object and HTML Attributes.
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- $originhrefattribute; for referenceurl- $origindata-urloraction(form) attribute; Used as API URL if setmethod- $origindata-methodormethodattribute; HTTP method to use in API call (default:'get')cacheRequest- $origindata-cache-requestattribute; iftrueflag XHR request to be cachedcacheResponse- $origindata-cache-responseattribute; iftrueuse cached response from Payload.jstype- jquery XHR request type (default:'json')selector- $origindata-selectorattribute; jQuery selector for the API $target that a template will be loaded intotemplate- $origin "data-template" attribute; name of the Handlebars template to load into the location specified bydata-selector(overridesdata-partialif also set)partial- $origindata-partialattribute; name of the Handlebars partial template to load into the location specified bydata-selectorevents- $origindata-publishattribute; space-separated list of events to have published to Payload.js subscribersrequestData- combination of JSON serialized form data and any JSON-encoded values within $origindata-formattributetemplateData- See Template Data belowloading- $origindata-loadingattribute; if "true" (or theloadingDefaultoption is true) the$targetelement will be cleared and have theloadingHtmlfrom Payload.js options inserted during API request handling.
Template Data
Every Handlebars template always has the following data available:
app- Any custom application data set atPayload.appDatarequest- href, url, method, and cacheKey for the API callview- A dictionary of alldata-*attributes from$origin
Payload.js Object Properties
options- Current set of options (see Payload.js Options)appData- Object for storing custom application data; provided asappwithin template datacache- Object containingresponsecache.