Show:

Q Class

Constructor

Item Index

Methods

Properties

Methods

_activateTools

(
  • toolElement
  • options
  • shared
)
private static

Given a tool's generated container div, constructs the corresponding JS tool object. Used internally. This basically calls the tool's constructor, passing it the correct prefix.

Parameters:

  • toolElement HTMLElement

    A tool's generated container div.

  • options Object

    Options that should be passed onto the tool

  • shared Mixed

    A shared pipe which we can use to fill

_initTools

(
  • toolElement
)
private static

Calls the init method of a tool. Used internally.

Parameters:

  • toolElement HTMLElement

    A tool's generated container div

action

(
  • uri
  • fields
  • [options]
)
static

Get the URL for an action

Parameters:

  • uri String

    A string of the form "Module/action" or an absolute url, which is returned unmodified.

  • fields Object

    Optional fields to append to the querystring. NOTE: only handles scalar values in the object.

  • [options] Object optional

    A hash of options, including:

    • [baseUrl] String optional

      A string to replace the default base url

    • [cacheBust] Number optional

      Number of milliseconds before a new cachebuster is appended

activate

(
  • elem
  • options
  • [callback]
)
Q.Promise static

Unleash this on an element to activate all the tools within it. If the element is itself an outer div of a tool, that tool is activated too.

Parameters:

  • elem HTMLElement | Q.Tool

    HTML element or existing tool to traverse and activate If this is empty, then Q.activate exits early

  • options Object

    Optional options to provide to tools and their children.

  • [callback] Function | Q.Event optional

    This will get called when the content has been completely activated. That is, after all the files, if any, have been loaded and all the constructors have run. It receives (elem, options, tools) as arguments, and the last tool to be activated as "this".

Returns:

Q.Promise:

Returns a promise with an extra .cancel() method to cancel the action

addEventListener

(
  • element
  • eventName
  • eventHandler
  • useCapture
  • hookStopPropagation
)
static

Add an event listener to an element

Parameters:

  • element HTMLElement

    An HTML element, window or other element that supports listening to events

  • eventName String | Array | Object

    A space-delimited string of event names, or an array of event names. You can also pass an object of { eventName: eventHandler } pairs, in which csae the next parameter would be useCapture.

  • eventHandler Function

    A function to call when the event fires

  • useCapture Boolean | Object

    Whether to use the capture instead of bubble phase. Ignored in IE8 and below. You can also pass {passive: true} and other such things here.

  • hookStopPropagation Boolean

    Whether to override Event.prototype.stopPropagation in order to capture the event when a descendant of the element tries to prevent

addScript

(
  • src
  • onload
  • [options]
)
Array static

Adds a reference to a javascript, if it's not already there

Parameters:

  • src String | Array

    The script url or an array of script urls

  • onload Function
  • [options] Object optional

    Optional. A hash of options, including options for Q.url() and these:

    • [duplicate] Boolean optional

      if true, adds script even if one with that src was already loaded

    • [skipIntegrity] Boolean optional

      if true, skips adding "integrity" attribute even if one can be calculated

    • [onError] Boolean optional

      optional function that may be called in newer browsers if the script fails to load. Its this object is the script tag.

    • [ignoreLoadingErrors] Boolean optional

      If true, ignores any errors in loading scripts.

    • [container] Boolean optional

      An element to which the stylesheet should be appended (unless it already exists in the document).

    • [returnAll] Boolean optional

      If true, returns all the script elements instead of just the new ones

Returns:

Array:

An array of SCRIPT elements

addStylesheet

(
  • href
  • media
  • onload
  • [options]
)
Array static

Adds a reference to a stylesheet, if it's not already there

Parameters:

  • href String
  • media String
  • onload Function
  • [options] Object optional

    Optional. A hash of options, including options for Q.url() and these:

    • [slotName] Boolean optional

      The slot name to which the stylesheet should be added, used to control the order they're applied in. Do not use together with container option.

    • [container] HTMLElement optional

      An element to which the stylesheet should be appended (unless it already exists in the document) Although this won't result in valid HTML, all browsers support it, and it enables the CSS to later be easily removed at runtime.

    • [skipIntegrity] Boolean optional

      if true, skips adding "integrity" attribute even if one can be calculated

    • [returnAll=false] Boolean optional

      If true, returns all the link elements instead of just the new ones

Returns:

Array:

Returns an aray of LINK elements

ajaxErrors

(
  • errors
  • fields
)
Object static

Turns AJAX errors returned by Q to a hash that might be useful for validating a form.

Parameters:

  • errors Object

    A hash of errors

  • fields Array

    Optional. An array of field names to restrict ourselves to. For each error, if none of the fields apply, then the error is assigned to the field named first in this array.

Returns:

Object:

Contains {fieldName: errorMessage} pairs.

ajaxExtend

(
  • what
  • slotNames
  • options
)
String | Object static

Extends a string or object to be used with AJAX

Parameters:

  • what String

    If a string, then treats it as a URL and appends ajax fields to the end of the querystring. If an object, then adds properties to it.

  • slotNames String | Object | Array

    If a string, expects a comma-separated list of slot names If an object or array, converts it to a comma-separated list

  • options Object

    Optional. A hash of options, including:

    • @param {String} [options.echo] A string to echo back. Used to keep track of responses
    • @param {String} [options.method] if set, adds a &Q.method=$method to the querystring
    • @param {String|Function} [options.callback] if a string, adds a "&Q.callback="+encodeURIComponent(callback) to the querystring.
    • @param {boolean} [options.iframe] if true, tells the server to render the response as HTML in an iframe, which should call the specified callback
    • @param {boolean} [options.loadExtras] if true, asks the server to load the extra scripts, stylesheets, etc. that are loaded on first page load
    • @param {Array} [options.idPrefixes] optional array of Q_Html::pushIdPrefix values for each slotName
    • @param {number} [options.timestamp] whether to include a timestamp (e.g. as a cache-breaker)

Returns:

String | Object:

Returns the extended string or object

alert

(
  • message
  • [options]
)
static

Provides replacement for default javascript alert() using Q front-end features, specifically dialogs. Shows dialog with customizable title, message and button label.

Parameters:

  • message String

    The only required parameter, this specifies text of the alert.

  • [options] Object optional

    An optional hash of options for Q.Dialog.push and also:

    • [title] String optional

      Optional parameter to override alert dialog title. Defaults to 'Alert'.

    • [onClose] Q.Event optional

      Optional, occurs when dialog is closed

assert

(
  • condition
  • complaint
)
static

Throws Q.Error with complaint if condition evaluates to something falsy

Parameters:

audio

(
  • url
  • handler
  • [options={}]
)
static

Loads an audio file and calls the callback when it's ready to play

Parameters:

  • url String
  • handler Function

    A function to run after the audio is ready to play

  • [options={}] Object optional

    Can be one of the following options

    • [canPlayThrough=true] Boolean optional

      Whether to wait until the audio can play all the way through before calling the handler.

baseUrl

(
  • where
)
String static

Given a hash of values, returns the hostname and port for connecting to PHP server running Q

Parameters:

  • where Object

    An object of field: value pairs

Returns:

String:

Something of the form "scheme://hostname:port" or "scheme://hostname:port/subpath"

batcher

(
  • batch
  • options
)
Function static

This function helps create "batch functions", which can be used in getter functions and other places to accomplish things in batches.

Parameters:

  • batch Function

    This is the function you must write to implement the actual batching functionality. It is passed the subjects, arguments, and callbacks that were collected by Q.batcher from the individual calls that triggered your batch function to be run. Your batch function is supposed to cycle through the callbacks array -- where each entry is the array of (one or more) callbacks the client passed during a particular call -- and Q.handle the appropriate one. NOTE: When receiving results from the server, make sure the order in which results are returned matches the order in which your batch function was provided the arguments from the individual calls. This will help you call the correct callbacks. Typically you would serialize the array of arguments e.g. into JSON when sending the request down to the server, and the server should also return an array of results that is in the same order.

  • options Object

    An optional hash of possible options, which can include:

    • [max=10] Boolean optional

      When the number of individual calls in the queue reaches this number, the batch function is run.

    • [ms=50] Boolean optional

      When this many milliseconds elapse without another call to the same batcher function, the batch function is run.

Returns:

Function:

It returns a function that the client can use as usual, but which, behind the scenes, queues up the calls and then runs a batch function that you write.

batcher.factory

(
  • collection
  • baseUrl
  • tail
  • slotName
  • fieldName
  • [options={}]
)
Function static

Used to create a basic batcher function, given only the url.

Parameters:

  • collection Object

    An object to contain all the batcher functions

  • baseUrl String

    The base url of the webservice built to support batch requests.

  • tail String

    The rest of the url of the webservice built to support batch requests.

  • slotName String

    The name of the slot to request. Defaults to "batch".

  • fieldName String

    The name of the data field. Defaults to "batch".

  • [options={}] Object optional

    Any additional options to pass to Q.req, as well as:

    • [max] Number optional

      Passed as option to Q.batcher

    • [ms] Number optional

      Passed as option to Q.batcher

    • [preprocess] Function optional

      Optional function calculating a data structure to JSON stringify into the data field

Returns:

Function:

A function with any number of non-function arguments followed by one function which is treated as a callback and passed (errors, content) where content is whatever is returned in the slots.

beforeUnload

(
  • notice
)
static

Call this function to set a notice that is shown when the page is almost about to be unloaded

Parameters:

  • notice String

    The notice to set. It should typically be worded so that "Cancel" cancels the unloading.

calculateKey

(
  • key
  • container
  • number
)
String static

Calculates a string key by considering the parameter that was passed, the tool being activated, and the page being activated. These keys can be used in methods of Q.Event, Q.Masks etc.

Parameters:

  • key String | Q.Tool
  • container Object

    in which the key will be used

  • number Number

    at which to start the loop for the default key generation

Returns:

clientId

() String static

Get a value that identifies the client in a fairly unique way. This is most useful to tell apart clients used by a particular user.

Returns:

confirm

(
  • message
  • callback:
  • [options]
)
static

Provides replacement for default javascript confirm() using Q front-end features, specifically dialogs. Shows dialog with customizable title, conrirmation message and buttons. The only major difference from regular confirm is that this implementation doesn't stop JS execution and thus it's impossible to synchronously return true | false when user presses 'Ok' or 'Cancel' and thereby callback is used to pass the user decision result.

Parameters:

  • message String

    The only required parameter, this specifies confirmation text.

  • callback: Function

    This will be called when dialog is closed, passing true | false depending on whether user clicked (tapped) 'Ok' or 'Cancel' button, respectively or null if the user closed the dialog.

  • [options] Object optional

    An optional hash of options for Q.Dialog.push and also:

    • [title='Confirm'] String optional

      to override confirm dialog title.

    • [ok='OK'] String optional

      to override confirm dialog 'Ok' button label, e.g. 'Yes'.

    • [cancel='Cancel'] String optional

      to override confirm dialog 'Cancel' button label, e.g. 'No'.

    • [noClose=true] Boolean optional

      set to false to show a close button

    • [onClose] Q.Event optional

      Optional, occurs when dialog is closed

copy

(
  • [fields=null]
  • levels
)
Object static

Makes a shallow copy of an object. But, if any property is an object with a "copy" method, or levels > 0, it recursively calls that method to copy the property.

Parameters:

  • [fields=null] Array optional

    Optional array of fields to copy. Otherwise copy all that we can.

  • levels Number

    Optional. Copy this many additional levels inside x if it is a plain object.

Returns:

Object:

Returns the shallow copy where some properties may have deepened the copy

currentScript

(
  • [stackLevels=0]
)
Object static

Gets information about the currently running script. Only works when called synchronously when the script loads.

Parameters:

  • [stackLevels=0] Number optional

    If called within a function that was called inside a script, put 1, if deeper put 2, etc.

Returns:

Object:

object with properties "src", "path" and "file"

debounce

(
  • original
  • milliseconds
  • [immediate=false]
  • defaultValue
)
Function static

Wraps a function and returns a wrapper that will call the function after calls stopped coming in for a given number of milliseconds. If the immediate param is true, the wrapper lets the function be called without waiting if it hasn't been called for the given number of milliseconds.

Parameters:

  • original Function

    The function to wrap

  • milliseconds Number

    The number of milliseconds

  • [immediate=false] Boolean optional

    if true, the wrapper also lets the function be called without waiting if it hasn't been called for the given number of milliseconds.

  • defaultValue Mixed

    Value to return whenever original function isn't called

Returns:

Function:

The wrapper function

diff

(
  • container
  • container
  • [comparator]
)
Array | Object static

Returns a container with the items in the first parameter that are not in the others

Parameters:

  • container Array | Object

    to subtract items from to form the result

  • container Array | Object

    whose items are subtracted in the result

  • [comparator] Function optional

    accepts item1, item2, index1, index2) and returns whether two items are equal

Returns:

Array | Object:

a container of the same type as container1, but without elements of container2

each

(
  • container,
  • callback
  • options
)
static

Iterates over elements in a container, and calls the callback. Use this if you want to avoid problems with loops and closures.

Parameters:

  • container, Array | Object | String | Number

    which can be an array, object or string. You can also pass up to three numbers here: from, to and optional step

  • callback Function | String

    A function which will receive two parameters index: the index of the current item value: the value of the current item Also can be a string, which would be the name of a method to invoke on each item, if possible. In this case the callback should be followed by an array of arguments to pass to the method calls.

  • options Object

    Can include the following:

    • [ascending=false] Boolean optional

      pass true here to traverse in ascending key order, false in descending.

    • [numeric=false] Boolean optional

      used together with ascending. Pass true to use numeric sort instead of string sort.

    • [sort] Function optional

      pass a comparator Function here to be used when sorting object keys before traversal. Also can pass a String naming the property on which to sort.

    • [hasOwnProperty=false] Boolean optional

      set to true to skip properties found on the prototype chain.

ensure

(
  • property
  • loader
  • callback
)
static

Use this to ensure that a property exists before running some javascript code. If something is undefined, loads a script or executes a function, calling the callback on success.

Parameters:

  • property Mixed

    The property to test for being undefined.

  • loader String | Function | Q.Event

    Something to execute if the property was undefined. If a string, this is interpreted as the URL of a javascript to load. If a function, this is called with the callback as the first argument. If an event, the callback is added to it.

  • callback Function

    The callback to call when the loader has been executed. This is where you would put the code that relies on the property being defined.

exports

() static

Exports one or more variables from a javascript file. The arguments you pass to this function will be passed as arguments to the callback of Q.require() whenever it requires the file in which this is called. They will also be saved, for subsequent calls of Q.require().

extend

(
  • target
  • levels
  • deep
  • anotherObject
  • namespace
)
static

Extends an object by merging other objects on top. Among other things, Q.Events can be extended with Q.Events or objects of {key: handler} pairs, Arrays can be extended by other arrays or objects. (If an array is being extended by an object with a "replace" property, the array is replaced by the value of that property.) You can also extend recursively, see the levels parameter.

Parameters:

  • target Object

    This is the first object. It winds up being modified, and also returned as the return value of the function.

  • levels Number

    Optional. Precede any Object with an integer to indicate that we should also copy that many additional levels inside the object.

  • deep Boolean | Number

    Optional. Precede any Object with a boolean true to indicate that we should also copy the properties it inherits through its prototype chain.

  • anotherObject Object

    Put as many objects here as you want, and they will extend the original one.

  • namespace String

    Optional namespace to use when extending encountered Q.Event objects

Returns:

The extended object.

find

(
  • elem
  • filter
  • callbackBefore
  • callbackAfter
  • options
  • shared
)
static

Finds all elements that contain a class matching the filter, and calls the callback for each of them.

Parameters:

  • elem HTMLElement | Array

    An element, or an array of elements, within which to search

  • filter String | RegExp | True | Null

    The name of the class or attribute to match

  • callbackBefore Function

    A function to run when a match is found (before the children). If it returns true, the Q.find function doesn't search further inside that element. If it returns false, the Q.find function stops searching. Otherwise, the Q.find function continues to search inside the element.

  • callbackAfter Function

    A function to run when a match is found (after the children) If it returns false, the Q.find function stops searching.

  • options Object

    Any options to pass to the callbacks as the second argument

  • shared Mixed

    An optional object that will be passed to each callbackBefore and callbackAfter

first

(
  • container
  • options
)
Mixed static

Returns the first non-undefined value found in a container Note: do not rely on object key ordering, it can vary in some browsers

Parameters:

Returns:

Mixed:

the value in the container, or undefined

firstErrorMessage

(
  • data
)
String | Null static

Try to find an error message assuming typical error data structures for the arguments

Parameters:

  • data Object

    An object where the errors may be found. You can pass as many of these as you want. If it contains "errors" property, then errors[0] is the first error. If it contains an "error" property, than that's the first error. Otherwise, for the first argument only, if it is nonempty, then it's considered an error.

Returns:

String | Null:

The first error message found, or null

firstKey

(
  • container
  • options
)
Number | String static

Returns the first key or index found in a container with a value that's not undefined Note: do not rely on object key ordering, it can vary in some browsers

Parameters:

Returns:

Number | String:

the index in the container, or null

formPost

(
  • action
  • [fields]
  • [method]
  • options
)
static

Uses a form to do a real POST, but doesn't have a callback Useful for convincing Safari to stop blocking third-party cookies Technically we could use AJAX and CORS instead, and then we could have a callback.

Parameters:

  • action String | HTMLElement

    The form action. You can also pass an HTML form element here, and skip fields and method.

  • [fields] Object optional

    The parameters of the form

  • [method] String optional

    The method with which to submit the form. Defaults to the form's method, or "post" if missing.

  • options Object | Boolean

    You can pass true here to just submit the form and load the results in a new page in this window. Or provide an optional object which can contain the following:

    • [target] String optional

      the name of a window or iframe to use as the target.

    • [iframe] HTMLElement optional

      the iframe to use. If not provided, this is filled to point to a newly created iframe object.

    • [onLoad] Q.Event optional

      callback to call when results are loaded in the iframe. Ignored if options.target is specified.

    • [form] HTMLElement optional

      the form to use. In this case, the action, fields and method are ignored.

getObject

(
  • name
  • [context=window]
  • [delimiter='.']
  • [create=undefined]
)
Object | Undefined static

Get a property from a delimiter-separated string, such as "A.B.C" Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format. You can also use it to resolve an object where it might be a string or array or something else.

Parameters:

  • name String | Array

    Path to a property, in the form "A.B.C" or ["A", "B", "C"] . If not a string or an array, it is simply returned.

  • [context=window] Object optional

    Optional. Object to use as root of path. Null may be passed.

  • [delimiter='.'] String optional

    The delimiter to use in the name

  • [create=undefined] Mixed optional

    Pass a value here to set with Q.setObject if nothing was there

Returns:

Object | Undefined:

Returns the originally stored value, or undefined if nothing is there

getter

(
  • original
  • [options={}]
)
Function static

Wraps a getter function to provide support for re-entrancy, cache and throttling. It caches based on all non-function arguments which were passed to the function. All functions passed in as arguments are considered as callbacks. Getter execution is considered complete when one of the callbacks is fired. If any other callback is fired, throttling may be influenced - i.e. throttleSize will increase by number of callbacks fired. If the original function has a "batch" property, it gets copied as a property of the wrapper function being returned. This is useful when calling Q.getter(Q.batcher(...)) Call method .forget with the same arguments as original getter to clear cache record and update it on next call to getter (if it happen)

Parameters:

  • original Function

    The original getter function to be wrapped Can also be an array of [getter, execute] which you can use if your getter does "batching", and waits a tiny bit before sending the batch request, to see if any more will be requested. In this case, the execute function is supposed to execute the batched request without waiting any more. If the original function returns false, the caching is canceled for that call.

  • [options={}] Object optional

    An optional hash of possible options, which include:

    • [prepare] Function optional

      This is a function that is run to copy-construct objects from cached data. It gets (subject, parameters, callback) and is supposed to call callback(subject2, parameters2)

    • [throttle] String optional

      an id to throttle on, or an Object that supports the throttle interface:

    • [throttleTry] Function optional

      function(subject, getter, args) - applies or throttles getter with subject, args

    • [throttleNext] Function optional

      function (subject) - applies next getter with subject

    • [throttleSize=100] Integer optional

      The size of the throttle, if it is enabled

    • [cache] Q.Cache | Boolean optional

      pass false here to prevent caching, or an object which supports the Q.Cache interface

Returns:

Function:

The wrapper function, which returns an object with a property called "result" which could be one of Q.getter.CACHED, Q.getter.WAITING, Q.getter.REQUESTING or Q.getter.THROTTLING . This function also contains Q.Events called onCalled, onResult and onExecuted.

handle

(
  • callables
  • callback
  • context
  • args
  • options
)
Number static

Used for handling callbacks, whether they come as functions, strings referring to functions (if evaluated), arrays or hashes.

Parameters:

  • callables Mixed

    The callables to call Can be a function, array of functions, object of functions, Q.Event or URL If it is a url, simply follow it with options, callback

  • callback Function

    You can pass a function here if callables is a URL

  • context Object

    The context in which to call them

  • args Array

    An array of arguments to pass to them

  • options Object

    If callables is a url, these are the options to pass to Q.loadUrl, if any. Also can include:

    • [dontReload=false] Boolean optional

      if this is true and callback is a url matching current url, it is not reloaded

    • [loadUsingAjax=false] Boolean optional

      if this is true and callback is a url, it is loaded using Q.loadUrl

    • [externalLoader] Function optional

      when using loadUsingAjax, you can set this to a function to suppress loading of external websites with Q.handle. Note: this will still not supress loading of external websites done with other means, such as window.location

    • [fields] Object optional

      optional fields to pass with any method other than "get"

    • [callback] String | Function optional

      if a string, adds a '&Q.callback='+encodeURIComponent(callback) to the querystring. If a function, this is the callback.

    • [loadExtras=true] Boolean optional

      if true, asks the server to load the extra scripts, stylesheets, etc. that are loaded on first page load

    • [target] String optional

      the name of a window or iframe to use as the target. In this case callables is treated as a url.

    • [slotNames] String | Array optional

      a comma-separated list of slot names, or an array of slot names

    • [quiet] Boolean optional

      defaults to false. If true, allows visual indications that the request is going to take place.

Returns:

Number:

The number of handlers executed

has

(
  • obj
  • key
)
Boolean static

Returns whether an object contains a property directly

Parameters:

Returns:

init

(
  • options
)
static

Initialize the Q javascript platform

Parameters:

  • options Object

    Supports the following options: "isLocalFile": defaults to false. Set this to true if you are calling Q.init from local file:/// context.

instanceOf

(
  • testing
  • Constructor
)
static

Use this instead of instanceof, it works with Q.mixin, even in IE

Parameters:

interpolateUrl

(
  • url
  • [additional={}]
)
String static

Interpolate some standard placeholders inside a url, such as {{AppName}} or {{PluginName}}

Parameters:

  • url String
  • [additional={}] Object optional

    Any additional substitutions

Returns:

String:

The url with substitutions applied

isArray

(
  • value
)
Boolean static

Tests if the value is an array

Parameters:

  • value Mixed

    The value to test

Returns:

Boolean:

Whether it is an array

isEmpty

(
  • o
)
Boolean static

Tests whether a variable contains a falsy value, or an empty object or array.

Parameters:

  • o Object

    The object to test.

Returns:

isInteger

(
  • value
  • [strictComparison=true]
)
Boolean static

Tests if the value is an integer

Parameters:

  • value Mixed

    The value to test

  • [strictComparison=true] Boolean optional

    Whether to test strictly for a number

Returns:

Boolean:

Whether it is an integer

isOnline

() Boolean static

Returns whether the client is currently connected to the 'net

Returns:

isPlainObject

(
  • x
)
Boolean static

Determines whether something is a plain object created within Javascript, or something else, like a DOMElement or Number

Parameters:

  • x Mixed

Returns:

Boolean:

Returns true only for a non-null plain object

isReady

() Boolean static

Returns whether Q.ready() has been called

Returns:

jsonRequest

(
  • fields
  • url
  • slotNames
  • callback
  • options
)
private static

A way to get JSON that is cross-domain. It uses script tags and JSONP callbacks. But may also use XHR if we have CORS enabled. Now this function is just an alias for Q.request

Parameters:

  • fields Object

    Optional object of fields to pass

  • url String

    The URL you pass will normally be automatically extended through Q.ajaxExtend

  • slotNames String | Array

    If a string, expects a comma-separated list of slot names If an array, converts it to a comma-separated list

  • callback Function

    The JSON will be passed to this callback function

  • options Object

    A hash of options, to be passed to Q.request

latest

(
  • key
  • ordinal
)
Number | Boolean static

Used to prevent overwriting the latest results on the client with older ones. Typically, you would call this function before making some sort of request, save the ordinal in a variable, and then pass it to the function again inside a closure. For example:

Parameters:

  • key String | Q.Tool

    Requests under the same key share the same incrementing ordinal

  • ordinal Number | Boolean

    Pass an ordinal that you obtained from a previous call to the function Pass true here to get the latest ordinal that has been passed so far to the method under this key, corresponding to the latest results seen.

Returns:

Number | Boolean:

If only key is provided, returns an ordinal to use. If ordinal is provided, then returns whether this is still the latest ordinal.

Example:

var ordinal = Q.latest(tool); requestSomeResults(function (err, results) { if (!Q.latest(tool, ordinal)) return; // otherwise, show the latest results on the client });

load

(
  • plugins
  • callback
  • options
)
static

Loads a plugin

Parameters:

loadHandlebars

(
  • callback
)
static

This function is called by Q to make sure that we've loaded the Handlebars library If you like, you can also call it yourself.

Parameters:

  • callback Function

    This function is called when the library is loaded

loadNonce

(
  • callback
  • context
  • args
)
static

This function is called by Q to make sure that we've loaded the session nonce. If you like, you can also call it yourself.

Parameters:

  • callback Function

    This function is called when the nonce is loaded

  • context Object

    The "this" to pass to the callback

  • args Array

    The arguments to pass to the callback

loadUrl

(
  • url
  • slotNames
  • callback
  • options
)
Q.Promise static

Parameters:

  • url String

    The url to load.

  • slotNames Array | String

    Optional, defaults to all application slots

  • callback Function

    Callback which is called when response returned and scripts, stylesheets and inline styles added, but before inline scripts executed. Receives response as its first agrument. May return DOM element or array of DOM elements on which to call Q.activate By default place slot content to DOM element with id "{slotName}_slot"

  • options Object

    Optional. An hash of options to pass to the loader, and can also include options for loadUrl itself:

    • [loader=Q.request] Function optional

      the actual function to load the URL. See Q.request documentation for more options.

    • [handler] Function optional

      the function to handle the returned data. Defaults to a function that fills the corresponding slot containers correctly.

    • [ignoreHistory=false] Boolean optional

      if true, does not push the url onto the history stack

    • [ignorePage=false] Boolean optional

      if true, does not process the links / stylesheets / script data in the response, and doesn't trigger deactivation of current page and activation of the new page

    • [ignoreLoadingErrors=false] Boolean optional

      If true, ignores any errors in loading scripts.

    • [ignoreHash=false] Boolean optional

      if true, does not navigate to the hash part of the URL in browsers that can support it

    • [fields] Object optional

      additional fields to pass via the querystring

    • [loadExtras=false] Boolean optional

      if true, asks the server to load the extra scripts, stylesheets, etc. that are loaded on first page load

    • [timeout=1500] Number | Boolean optional

      milliseconds to wait for response, before showing cancel button and triggering onTimeout event, if any, passed to the options

    • [quiet=false] Boolean optional

      if true, allows visual indications that the request is going to take place.

    • [slotNames] String | Array optional

      an array of slot names to request and process (default is all slots in Q.info.slotNames)

    • [idPrefixes] Array optional

      optional array of values to pass to PHP method Q_Html::pushIdPrefix for each slotName

    • [retainSlots] Object optional

      an object of {slotName: whetherToRetain} pairs, retained slots aren't requested

    • [slotContainer] Boolean optional

      optional function taking (slotName, response) and returning the element, if any, to fill for that slot

    • [replaceElements] Array optional

      array of elements or ids of elements in the document to replace. Overrides "data-q-retain" attributes but not retainSlots option.

    • [key='Q'] String optional

      If a response to the request initiated by this call to Q.loadUrl is preceded by another call to Q.loadUrl with the same key, then the response handler is not run for that response (since a newer one is pending or arrived).

    • [onTimeout] Q.Event optional

      handler to call when timeout is reached. Receives function as argument - the function might be called to cancel loading.

    • [onResponse] Q.Event optional

      handler to call when the response comes back but before it is processed

    • [onError] Q.Event optional

      event for when an error occurs, by default shows an alert

    • [onLoad] Q.Event optional

      event which occurs when the parsed data comes back from the server

    • [onActivate] Q.Event optional

      event which occurs when all Q.activate's processed and all script lines executed

    • [onLoadStart] Q.Event optional

      if "quiet" option is false, anything here will be called after the request is initiated.

    • [onLoadEnd] Q.Event optional

      if "quiet" option is false, anything here will be called after the request is fully completed.

Returns:

Q.Promise:

Returns a promise with an extra .cancel() method to cancel the action

milliseconds

(
  • sinceEpoch
)
Number

Returns the number of milliseconds since the first call to this function i.e. since this script was parsed.

Parameters:

  • sinceEpoch Boolean

    Defaults to false. If true, just returns the number of milliseconds in the UNIX timestamp.

Returns:

Number:

The number of milliseconds, with fractional part

milliseconds

(
  • sinceEpoch
)
Float static

Returns the number of milliseconds since the first call to this function (i.e. since script started).

Parameters:

  • sinceEpoch Boolean

    Defaults to false. If true, just returns the number of milliseconds in the UNIX timestamp.

Returns:

Float:

The number of milliseconds, with fractional part

mixin

(
  • A
  • B
)
static

Mixes in one or more classes. Useful for inheritance and multiple inheritance.

Parameters:

  • A Function

    The constructor corresponding to the "class" we are mixing functionality into This function will get the following members set: __mixins: an array of [B, C, ...] constructors(subject, params): a method to call the constructor of all mixin classes, in order. Pass "this" as the first argument. staticProperty(property): a method for getting a property name

  • B Function

    One or more constructors representing "classes" to mix functionality from They will be tried in the order they are provided, meaning methods from earlier ones override methods from later ones.

nodeUrl

(
  • where
)
String static

Given an index and field values, returns the hostname and port for connecting to a Node.js server running Q

Parameters:

  • where Object

    An object of field: value pairs

Returns:

String:

"scheme://hostname:port"

normalize

(
  • text
  • replacement
  • characters
  • numChars
  • [keepCaseIntact=false]
)
String static

Normalizes text by converting it to lower case, and replacing all non-accepted characters with underscores.

Parameters:

  • text String

    The text to normalize

  • replacement String

    Defaults to '_'. A string to replace one or more unacceptable characters. You can also change this default using the config Db/normalize/replacement

  • characters String

    Defaults to '/[^A-Za-z0-9]+/'. A regexp characters that are not acceptable. You can also change this default using the config Db/normalize/characters

  • numChars Number

    The maximum length of a normalized string. Default is 200.

  • [keepCaseIntact=false] Boolean optional

    If true, doesn't convert to lowercase

Returns:

String:

the normalized string

objectWithPrototype

(
  • original
)
Derived static

Creates a copied object which you can extend, using existing object as prototype

Parameters:

  • original Derived

Returns:

Derived:

once

(
  • original
  • defaultValue
)
Function static

Wraps a function and returns a wrapper that will call the function at most once.

Parameters:

  • original Function

    The function to wrap

  • defaultValue Mixed

    Value to return whenever original function isn't called

Returns:

Function:

The wrapper function

page

(
  • page
  • handler
  • key
)
static

Use this function to set handlers for when the page is loaded or unloaded.

Parameters:

  • page String

    "$Module/$action" or a more specific URI string, or "" to handle all pages

  • handler Function

    A function to run after the page loaded. If the page is already currently loaded (i.e. it is the latest loaded page) then the handler is run right away. The handler can optionally returns another function, which will be run when the page is unloaded. After a page is unloaded, all the "unloading" handlers added in this way are removed, so that the next time the "loading" handlers run, they don't create duplicate "unloading" handlers.

  • key String

    Use this to identify the entity setting the handler, e.g. "Users/authorize". If the key is undefined, it will be automatically set to "Q". To force no key, pass null here. Since "loading" handlers are not automatically removed, they can accumulate if the key was null. For example, if an AJAX call would execute Javascript such as Q.page(uri, handler, null), this could lead to frustrating bugs as event handlers are registered multiple times, etc.

parseQueryString

(
  • queryString
  • keys
)
Object static

Parses a querystring

Parameters:

  • queryString String

    The string to parse

  • keys Array

    Optional array onto which the keys are pushed

Returns:

Object:

an object with the resulting {key: value} pairs

pipe

() Q.Pipe static

A convenience method for constructing Q.Pipe objects and is really here just for backward compatibility.

Returns:

pluginBaseUrl

()

You can override this function to do something special

preventRecursion

(
  • name
  • original
  • defaultValue
)
Function static

Wraps a function and causes it to return early if called recursively. Use sparingly, since most functions should make guarantees about postconditions.

Parameters:

  • name String

    The name of the function, passed explicitly

  • original Function

    The function or method to wrap

  • defaultValue Mixed

    Value to return whenever original function isn't called

Returns:

Function:

The wrapper function

promisify

(
  • getter
  • useSecondArgument
)
Function static

Takes a function and returns a version that returns a promise

Parameters:

  • getter Function

    A function that takes one callback and passes err as the first parameter to it

  • useSecondArgument Boolean

    whether to resolve the promise with the second argument instead of with "this"

Returns:

Function:

a wrapper around the function that returns a promise, extended with the original function's return value if it's an object

prompt

(
  • [message='Enter
  • callback:
  • [options]
)
static

Provides replacement for default javascript prompt() using Q front-end features, specifically dialogs. Shows dialog with customizable title, message, input field placeholder and button label. Unlike a regular JS prompt, the entered value is passed asynchronously using callback.

Parameters:

  • [message='Enter String

    a value'] Optional, specifies text before input field useful to ask user to enter something (e.g. 'Enter your name').

  • callback: Function

    This will be called when dialog is closed, passing the entered value as a string, or null if the dialog was dismissed with the close button

  • [options] Object optional

    An optional hash of options for Q.Dialog.push and also:

    • [title='Prompt'] String optional

      to override confirm dialog title.

    • [placeholder=''] String optional

      to set a placeholder in the textbox

    • [maxlength=1000] Number optional

      the maximum length of the input

    • [ok='OK'] String optional

      to override confirm dialog 'Ok' button label, e.g. 'Yes'.

    • [cancel='Cancel'] String optional

      to override confirm dialog 'Cancel' button label, e.g. 'No'.

    • [noClose=true] Boolean optional

      set to false to show a close button

    • [onClose] Q.Event optional

      Optional, occurs when dialog is closed

queryString

(
  • fields
  • keys
  • returnAsObject
)
String | Object static

Serialize a plain object, with possible sub-objects, into an http querystring.

Parameters:

  • fields Object | String | HTMLElement

    The object to serialize into a querystring that can be sent to PHP or something. The algorithm will recursively walk the object, and skip undefined values. You can also pass a form element here. If you pass a string, it will simply be returned.

  • keys Array

    An optional array of keys into the object, in the order to serialize things

  • returnAsObject Boolean

    Pass true here to get an object of {fieldname: value} instead of a string

Returns:

String | Object:

A querystring that can be used with HTTP requests.

queue

(
  • original
  • milliseconds
)
Function static

Wraps a function and returns a wrapper that adds the function to a queue of functions to be called one by one at most once every given milliseconds.

Parameters:

  • original Function

    The function to wrap

  • milliseconds Number

    The number of milliseconds, defaults to 0

Returns:

Function:

The wrapper function

ready

() static

This is called when the DOM is ready

removeElement

(
  • element,
  • removeTools
)
static

Remove an element from the DOM and try to clean up memory as much as possible

Parameters:

  • element, HTMLElement | Array

    or array of elements, or object of elements

  • removeTools Boolean

    whether to properly remove the tools before removing the element

removeEventListener

(
  • element
  • eventName
  • eventHandler
  • useCapture return
)
static

Remove an event listener from an element

Parameters:

  • element HTMLElement
  • eventName String
  • eventHandler Function
  • useCapture return Boolean

    {boolean} Should normally return true, unless listener could not be found or removed

replace

(
  • container
  • source
  • options
)
HTMLElement static

Replaces the contents of an element and does the right thing with all the tools in it

Parameters:

  • container HTMLElement

    A existing HTMLElement whose contents are to be replaced with the source Tools found in the existing DOM which have data-Q-retain attribute are actually retained unless the tool replacing them has a data-Q-replace attribute. You can update the tool by implementing a handler for tool.Q.onRetain, which receives the old Q.Tool object, the new options and incoming element. After the event is handled, the tool's state will be extended with these new options.

  • source Element | String

    An HTML string or a Element which is not part of the DOM

  • options Object

    Optional. A hash of options, including:

    • [replaceElements] Array optional

      array of elements or ids of elements in the document to replace, even if they have "data-q-retain" attributes.

    • [animation] Boolean optional

      To animate the transition, pass an object here with optional "duration", "ease" and "callback" properties.

Returns:

HTMLElement:

Returns the container element if successful

req

(
  • uri
  • slotNames
  • callback
  • options
)
Q.Request static

The easiest way to make direct web service requests in Q

Parameters:

  • uri String

    A string of the form "Module/action"

  • slotNames String | Array

    If a string, expects a comma-separated list of slot names. If an array, converts it to a comma-separated list.

  • callback Function

    The err and parsed content will be passed to this callback function, (unless parse is false, in which case the raw content is passed as a String), followed by a Boolean indicating whether a redirect was performed.

  • options Object

    A hash of options, to be passed to Q.request and Q.action (see their options).

Returns:

Q.Request:

Object corresponding to the request

request

(
  • fields
  • url
  • slotNames
  • callback
  • options
)
Q.Request static

A way to make requests that is cross-domain. Typically used for requesting JSON or various templates. It uses script tags and JSONP callbacks for remote domains, and prefers XHR for the local domain.

Parameters:

  • fields Object

    Optional object of fields to pass

  • url String

    The URL you pass will normally be automatically extended through Q.ajaxExtend

  • slotNames String | Array

    If a string, expects a comma-separated list of slot names If an array, converts it to a comma-separated list

  • callback Function

    The err and parsed content will be passed to this callback function, (unless parse is false, in which case the raw content is passed as a String), followed by a Boolean indicating whether a redirect was performed.

  • options Object

    A hash of options, including options that would be passed to Q.url(), but also these:

    • [method] String optional

      if set, adds a &Q.method= that value to the querystring, default "get"

    • [fields] Object optional

      optional fields to pass with any method other than "get"

    • [form] HTMLElement optional

      if specified, then the request is made by submitting this form, temporarily extending it with any fields passed in options.fields, and possibly overriding its method with whatever is passed to options.method .

    • [resultFunction="result"] String optional

      The path to the function to handle inside the contentWindow of the resulting iframe, e.g. "Foo.result". Your document is supposed to define this function if it wants to return results to the callback's second parameter, otherwise it will be undefined

    • [idPrefixes] Array optional

      optional array of Q_Html::pushIdPrefix values for each slotName

    • [skipNonce] Boolean optional

      if true, skips loading of the nonce

    • [xhr] Object optional

      set to false to avoid XHR. Or set to true, to try to make xhr based on "method" option. Or pass an object with properties to merge onto the xhr object, including a special "sync" property to make the call synchronous. Or pass a function which will be run before .send() is executed. First parameter is the xhr object, second is the options.

    • [preprocess] Function optional

      an optional function that takes the xhr object before the .send() is invoked on it

    • [parse] Boolean optional

      set to false to pass the unparsed string to the callback

    • [extend=true] Boolean optional

      if false, the URL is not extended with Q fields.

    • [query=false] Boolean optional

      if true simply returns the query url without issuing the request

    • [callbackName] String optional

      if set, the URL is not extended with Q fields and the value is used to name the callback field in the request.

    • [duplicate=true] Boolean optional

      you can set it to false in order not to fetch the same url again

    • [quiet=true] Boolean optional

      this option is just passed to your onLoadStart/onLoadEnd handlers in case they want to respect it.

    • [timestamp] Boolean optional

      whether to include a timestamp (e.g. as a cache-breaker)

    • [onRedirect=Q.handle] Function optional

      if set and response data.redirect.url is not empty, automatically call this function.

    • [timeout=1500] Boolean optional

      milliseconds to wait for response, before showing cancel button and triggering onTimeout event, if any, passed to the options

    • [onTimeout] Q.Event optional

      handler to call when timeout is reached. First argument is a function which can be called to cancel loading.

    • [onResponse] Q.Event optional

      handler to call when the response comes back but before it is processed

    • [onProcessed] Q.Event optional

      handler to call when a response was processed

    • [onLoadStart] Q.Event optional

      if "quiet" option is false, anything here will be called after the request is initiated

    • [onLoadEnd] Q.Event optional

      if "quiet" option is false, anything here will be called after the request is fully completed

Returns:

Q.Request:

Object corresponding to the request

require

(
  • src
  • callback
)
static

Loads the Javascript file and then executes the callback, The code in the file is supposed to synchronously call Q.exports() and pass arguments to it which are then passed as arguments to the callback. If the code was loaded and Q.exports() was already called, then the callback is called with saved arguments.

Parameters:

  • src String

    The src of the script to load

  • callback Function

    Always called asynchronously

sessionId

() String static

Get the value of the session cookie

Returns:

sessionName

() String static

Get the name of the session cookie

Returns:

setObject

(
  • name
  • value
  • [context=window]
  • [delimiter='.']
)
Object | Undefined static

Set an object from a delimiter-separated string, such as "A.B.C" Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format. Objects are created as needed along path. Another way to call this function is to pass an object of {name: value} pairs as the first parameter and context as an optional second parameter. Then the return value is an object of the usual return values.

Parameters:

  • name String | Array

    Path to a property, in the form "A.B.C" or ["A", "B", "C"]

  • value Anything

    value or object to place at location given by name

  • [context=window] Object optional

    Optional. Object to use as root of path.

  • [delimiter='.'] String optional

    The delimiter to use in the name

Returns:

Object | Undefined:

Returns the passed value if setting is successful or undefined if not.

shuffle

(
  • arr
)
static

Shuffles an array

Parameters:

  • arr Array

    The array that gets passed here is shuffled in place

take

(
  • source
  • fields
)
Object static

Copies a subset of the fields in an object

Parameters:

  • source Object

    An Object from which to take things

  • fields Array | Object

    An array of fields to take Or an Object of fieldname: default pairs

Returns:

throttle

(
  • original
  • milliseconds
  • delayedFinal
  • defaultValue
)
Function static

Wraps a function and returns a wrapper that will call the function at most once every given milliseconds.

Parameters:

  • original Function

    The function to wrap

  • milliseconds Number

    The number of milliseconds

  • delayedFinal Boolean

    Whether the wrapper should execute the latest function call after throttle opens again, useful for e.g. following a mouse pointer that stopped.

  • defaultValue Mixed

    Value to return whenever original function isn't called

Returns:

Function:

The wrapper function

trigger

(
  • eventName
  • element
  • args
)
static

Triggers a method or Q.Event on all the tools inside a particular element, traversing in a depth-first manner.

Parameters:

  • eventName String

    Required, the name of the method or Q.Event to trigger

  • element HTMLElement

    Optional element to traverse from (defaults to document.body).

  • args Array

    Any additional arguments that would be passed to the triggered method or event

typeOf

(
  • value
)
String static

Returns the type of a value

Parameters:

  • value Mixed

Returns:

url

(
  • what
  • fields
  • [options]
)
static

Obtain a URL to request. Takes into account the Q_ct and Q_ut cookies in order to work with Cordova file bundles, as well as Q.updateUrls()

Parameters:

  • what Object | String | Null

    Usually the stuff that comes after the base URL. If you don't provide this, then it just returns the Q.info.baseUrl

  • fields Object

    Optional fields to append to the querystring. Fields containing null and undefined are skipped. NOTE: only handles scalar values in the object.

  • [options] Object optional

    A hash of options, including:

    • [baseUrl] String optional

      A string to replace the default base url

    • [cacheBust] Number optional

      Number of milliseconds before a new cachebuster is appended

    • [info] Object optional

      if passed, extends this object with any info about the url

uuid

() static

Call this function to get an rfc4122 version 4 compliant id for the current client

Properties

Promise

Function

By default this is set to the root Promise object, which may be undefined in browsers such as Internet Explorer. You can load a Promises library and set Q.Promise to the Promise constructor before including Q.js, to ensure Promises are used by Q.getter and other functions.

text

Object

Store and customize your text strings under Q.text

Events

beforeActivate

This event occurs every time before something is activated

beforeInit

This event occurs right before Q javascript library is initialized

beforeReplace

This event occurs before replacing the contents of an element

onActivate

This event occurs every time after something is activated

onDOM

This event occurs when the DOM is ready

onHandleOpenUrl

This event occurs when an app url is open in Cordova

onHashChange

This event tracks the window.hashchange event

onInit

This event occurs when Q javascript library has just been initialized

onJQuery

This event occurs when jQuery has been loaded

onLayout

Call this function to get an event which occurs every time Q.layout() is called on the given element or one of its parents.

Event Payload:

  • [element=document.documentElement] Element optional

onLayout

This event is convenient for doing stuff when the window scrolls

onLoad

This event tracks the window.onload event

onOffline

This event tracks the window.onoffline event, when online connection is lost

onOnline

This event tracks the window.ononline event, when browser goes online

onPopState

This event tracks the window.popstate event

onReady

This event occurs when the DOM and entire environment is ready

onUnload

This event tracks the window.onunload event

onVisibilityChange

This event tracks the document.onvisibilitychange event, when online connection is lost