Attach an API event to an input, by default, it will occur oninput
. Attach an API event to a button, onclick
. State management is built in: rate throttling, UI state changes like active, loading, disabled, min/max request lengths and more.
Create named actions like 'follow user'
and have API handle URL templating, parameters, and other annoyances for you.
Easily tie server events like AJAX loading elements using intuitive defaults based on the context inside your interface. Set maximum and minimum request times, toggle between UI states, and easily sync state between multiple elements with the same API actions.
View your API request as it occurs in your web console, get errors if required url variables are missing, and useful performance metrics.
Defining Your API
Setting API Endpoints
API works best by defining named API actions which can be converted to URLs for each request.
You must define your endpoints once in your application before making requests. Usually this is done in a central configuration file included on each page.
URLs listed in your API can include required parameters and optional parameters which may be adjusted for each call.
Required Parameters
{variable}
Optional Parameters
{/variable}
Working with URLs
Named API actions are offered for convenience and maintanability, but are not required. You can also specify the url in each request, templated or not.
Querying API Actions
Attaching API Events
Any element can have an API action attached directly to it. By default the action will occur on the most appropriate event for the type of element. For example a button will assume onclick
or an input oninput
, or a form onsubmit
.
Specifying DOM Events
If you need to override what action an API event occurs on you can use the on
parameter.
Calling Immediately
If you require API action to occur immediately use on: 'now'
. This will still trigger the same state updates to the invoked element, but will occur immediately.
Keep in mind passing a new settings object will destroy all previously attached events. If you want to preserve the events, you can trigger a new request with the the query
behavior
Setting-up Requests
URL Variables
If your API urls include templated variables they will be replaced during your request by one of four possible ways (listed in order of inheritance).
Automatically Routed Data
Some special values are available for routing without additional set-up
Variable | Description | Available for |
---|---|---|
text | current text value of element | All DOM elements |
value | current input value of element | All input elements |
Request Information in Data Attributes
You can include url values as html5 metadata attributes
This is often easiest to include unique url data for each triggering element, for example, many follow buttons will trigger the same endpoint, but each will have its own user id.
As a convenience, you can also specify your API action in metadata, to allow you to instantiate multiple types of api actions in one statement.
Data specified in Javascript
URL variable, and GET/POST data can be specified at run-time in the javascript object
Adjusting Request in Before Send
All run settings, not just url data, can be adjusted in a special callback beforeSend
which occurs before the API request is sent.
Cancelling Requests
BeforeSend can also be used to check for special conditions for a request to be made. It the beforeSend
callback returns false, the request will be cancelled.
Sending Data
Automatically Routed Data
Calling API on any element inside of a form, will automatically include serialized form content in your request when using a special setting serializeForm
, or using a form as the stateContext
.
Unlike jQuery's serialize, data will be serialized as a javascript object using macek's serialize object.
Benefits of Structured Data
- Serialized Form Data can be modified in javascript in
beforeSend
- Structured data can be used by using names like
name="user[name]"
in your form - Form data will automatically be converted to useful values, for instance, checkbox to to
boolean
values.
Included in Javascript
POST or GET data can be included, when setting up API requests, through automatic inclusion, or during the beforeSend callback. This data will be joined together
Server Responses
Determining Success
API is designed to work with APIs that return JSON
objects. Instead of providiing success and failure callbacks based on the HTTP response of the request. A request is considered succesful only if the returned JSON value passes a successTest
.
For example you might expect all successful JSON responses to return a top level property signifying the success of the response
The success test function recieves the servers json response, and returns whether the result should be considered successful. Succesful results will trigger onSuccess
, invalid results onFailure
.
onError
will only trigger on XHR errors (except due to page navigation like clicking a link), but not invalid JSON responses.
Controlling State
API State Management
Many elements like button, input, and form have loading, disabled, and active states defined.
States adjust class names on the triggering element or on the element specified by settings.stateContext
.
Using stateContext
allows you to easily do things like, trigger a loading state on a form when a submit button is pressed.
States Included in API Module
State | Description | API event |
---|---|---|
loading | Indicates a user needs to wait | XHR has initialized |
error | Indicates an error has occurred | XHR Request returns error (does not trigger onAbort caused by page change, or if successTest fails). Stays visible for settings.errorDuration |
Coupling with State Module
Initializing an API action with the state module gives you more granular control over UI states, like setting an activated or de-activated state and the ability to adjust text values for each state:
For additional examples of the possibilities available with state behaviors check the state module documentation
States Included in State Module
State | Description | Occurs on |
---|---|---|
inactive | Default state | |
active | Selected state | Toggled on succesful API request |
activate | Explains activating action | On hover if inactive |
deactivate | Explains deactivating action | On hover if active |
hover | Explains interaction | On hover in all states, overrides activate/deactivate |
disabled | Indicates element cannot be interacted | Triggered programatically. Blocks API requests. |
flash | Text-only state used to display a temporary message | Triggered programatically |
success | Indicates user action was a success | Triggered programatically |
warning | Indicates there was an issue with a user action | Triggered programatically |
Needs to be written still...
API
Behavior
Default | Description | |
---|---|---|
on | auto | When API event should occur |
filter |
.disabled
|
Selector filter for elements that should not be triggerable |
stateContext | this | UI state will be applied to this element, defaults to triggering element. |
defaultData | true | Whether to automatically include default data like {value} and {text} |
serializeForm | false | Whether to serialize closest form and include in request |
loadingDuration | 0 | Minimum duration to show loading indication |
errorDuration | 2000 | Duration in milliseconds to show error state after request error. |
Request Settings
Default | Description | Possible Values | |
---|---|---|---|
action | Named API action for query, originally specified in $.fn.settings.api | String or false | |
url | false | Templated URL for query, will override specified action | String or false |
urlData | false | Variables to use for replacement | |
method | get | Method for transmitting request to server | post, get |
dataType | JSON | Expected data type of response | xml, json, jsonp, script, html, text |
data | {} | POST/GET Data to Send with Request |
Callbacks
Context | Description | |
---|---|---|
beforeSend(settings) | initialized element | Allows modifying settings before request, or cancelling request |
beforeXHR(xhrObject) | Allows modifying XHR object for request | |
onSuccess(response, element) | state context | Callback on response object that passed successTest |
onFailure(response, element) | state context | Callback on response object that fails successTest |
onError(errorMessage, element) | state context | Callback on server error from returned status code, or XHR failure. |
onAbort(errorMessage, element) | state context | Callback on abort caused by user clicking a link or manually cancelling request |
onComplete(response, element) | state context | Callback on request complete regardless of conditions |
Module
These settings are native to all modules, and define how the component ties content to DOM attributes, and debugging settings for the module.
Default | Description | |
---|---|---|
name | API | Name used in log statements |
namespace | api | Event namespace. Makes sure module teardown does not effect other events attached to an element. |
regExp |
regExp : {
required: /\{\$*[A-z0-9]+\}/g,
optional: /\{\/\$*[A-z0-9]+\}/g,
}
|
Regular expressions used for template matching |
selector |
selector: {
form: 'form'
}
|
Selectors used to find parts of a module |
className |
className: {
loading : 'loading',
error : 'error'
}
|
Class names used to determine element state |
metadata |
metadata: {
action : 'action',
request : 'request',
xhr : 'xhr'
}
|
Metadata used to store xhr and response promise |
debug | false | Debug output to console |
performance | false | Show console.table output with performance metrics |
verbose | false | Debug output includes all internal behaviors |
errors |
// errors
error : {
beforeSend : 'The before send function has aborted the request',
error : 'There was an error with your request',
exitConditions : 'API Request Aborted. Exit conditions met',
JSONParse : 'JSON could not be parsed during error handling',
legacyParameters : 'You are using legacy API success callback names',
missingAction : 'API action used but no url was defined',
missingSerialize : 'Required dependency jquery-serialize-object missing, using basic serialize',
missingURL : 'No URL specified for api event',
noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.',
parseError : 'There was an error parsing your request',
requiredParameter : 'Missing a required URL parameter: ',
statusMessage : 'Server gave an error: ',
timeout : 'Your request timed out'
}
|