Q Class
Constructor
Q
()
Item Index
Methods
- _activateTools static
- _initTools static
- action static
- activate static
- addEventListener static
- addScript static
- addStylesheet static
- ajaxErrors static
- ajaxExtend static
- alert static
- assert static
- audio static
- baseUrl static
- batcher static
- batcher.factory static
- beforeUnload static
- calculateKey static
- clientId static
- confirm static
- cookie static
- copy static
- currentScript static
- debounce static
- diff static
- each static
- ensure static
- exports static
- extend static
- find static
- first static
- firstErrorMessage static
- firstKey static
- formPost static
- getObject static
- getter static
- handle static
- has static
- init static
- instanceOf static
- interpolateUrl static
- isArray static
- isEmpty static
- isInteger static
- isOnline static
- isPlainObject static
- isReady static
- jsonRequest static
- latest static
- load static
- loadHandlebars static
- loadNonce static
- loadUrl static
- milliseconds
- milliseconds static
- mixin static
- nodeUrl static
- normalize static
- objectWithPrototype static
- once static
- page static
- parseQueryString static
- pipe static
- pluginBaseUrl
- preventRecursion static
- promisify static
- prompt static
- queryString static
- queue static
- ready static
- removeElement static
- removeEventListener static
- replace static
- req static
- request static
- require static
- sessionId static
- sessionName static
- setObject static
- shuffle static
- take static
- throttle static
- trigger static
- typeOf static
- url static
- uuid static
Methods
_activateTools
-
toolElement
-
options
-
shared
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
HTMLElementA tool's generated container div.
-
options
ObjectOptions that should be passed onto the tool
-
shared
MixedA shared pipe which we can use to fill
_initTools
-
toolElement
Calls the init method of a tool. Used internally.
Parameters:
-
toolElement
HTMLElementA tool's generated container div
action
-
uri
-
fields
-
[options]
Get the URL for an action
activate
-
elem
-
options
-
[callback]
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.ToolHTML element or existing tool to traverse and activate If this is empty, then Q.activate exits early
-
options
ObjectOptional options to provide to tools and their children.
-
[callback]
Function | Q.Event optionalThis 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:
Returns a promise with an extra .cancel() method to cancel the action
addEventListener
-
element
-
eventName
-
eventHandler
-
useCapture
-
hookStopPropagation
Add an event listener to an element
Parameters:
-
element
HTMLElementAn HTML element, window or other element that supports listening to events
-
eventName
String | Array | ObjectA 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
FunctionA function to call when the event fires
-
useCapture
Boolean | ObjectWhether 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
BooleanWhether to override Event.prototype.stopPropagation in order to capture the event when a descendant of the element tries to prevent
addScript
-
src
-
onload
-
[options]
Adds a reference to a javascript, if it's not already there
Parameters:
-
src
String | ArrayThe script url or an array of script urls
-
onload
Function -
[options]
Object optionalOptional. A hash of options, including options for Q.url() and these:
-
[duplicate]
Boolean optionalif true, adds script even if one with that src was already loaded
-
[skipIntegrity]
Boolean optionalif true, skips adding "integrity" attribute even if one can be calculated
-
[onError]
Boolean optionaloptional function that may be called in newer browsers if the script fails to load. Its this object is the script tag.
-
[ignoreLoadingErrors]
Boolean optionalIf true, ignores any errors in loading scripts.
-
[container]
Boolean optionalAn element to which the stylesheet should be appended (unless it already exists in the document).
-
[returnAll]
Boolean optionalIf true, returns all the script elements instead of just the new ones
-
Returns:
An array of SCRIPT elements
addStylesheet
-
href
-
media
-
onload
-
[options]
Adds a reference to a stylesheet, if it's not already there
Parameters:
-
href
String -
media
String -
onload
Function -
[options]
Object optionalOptional. A hash of options, including options for Q.url() and these:
-
[slotName]
Boolean optionalThe 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 optionalAn 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 optionalif true, skips adding "integrity" attribute even if one can be calculated
-
[returnAll=false]
Boolean optionalIf true, returns all the link elements instead of just the new ones
-
Returns:
Returns an aray of LINK elements
ajaxErrors
-
errors
-
fields
Turns AJAX errors returned by Q to a hash that might be useful for validating a form.
Parameters:
Returns:
Contains {fieldName: errorMessage} pairs.
ajaxExtend
-
what
-
slotNames
-
options
Extends a string or object to be used with AJAX
Parameters:
-
what
StringIf 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 | ArrayIf a string, expects a comma-separated list of slot names If an object or array, converts it to a comma-separated list
-
options
ObjectOptional. 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)
alert
-
message
-
[options]
Provides replacement for default javascript alert() using Q front-end features, specifically dialogs. Shows dialog with customizable title, message and button label.
assert
-
condition
-
complaint
Throws Q.Error with complaint if condition evaluates to something falsy
audio
-
url
-
handler
-
[options={}]
Loads an audio file and calls the callback when it's ready to play
baseUrl
-
where
Given a hash of values, returns the hostname and port for connecting to PHP server running Q
Parameters:
-
where
ObjectAn object of field: value pairs
Returns:
Something of the form "scheme://hostname:port" or "scheme://hostname:port/subpath"
batcher
-
batch
-
options
This function helps create "batch functions", which can be used in getter functions and other places to accomplish things in batches.
Parameters:
-
batch
FunctionThis 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
ObjectAn optional hash of possible options, which can include:
Returns:
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={}]
Used to create a basic batcher function, given only the url.
Parameters:
-
collection
ObjectAn object to contain all the batcher functions
-
baseUrl
StringThe base url of the webservice built to support batch requests.
-
tail
StringThe rest of the url of the webservice built to support batch requests.
-
slotName
StringThe name of the slot to request. Defaults to "batch".
-
fieldName
StringThe name of the data field. Defaults to "batch".
-
[options={}]
Object optionalAny additional options to pass to Q.req, as well as:
Returns:
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
Call this function to set a notice that is shown when the page is almost about to be unloaded
Parameters:
-
notice
StringThe notice to set. It should typically be worded so that "Cancel" cancels the unloading.
calculateKey
-
key
-
container
-
number
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:
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]
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
StringThe only required parameter, this specifies confirmation text.
-
callback:
FunctionThis 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 optionalAn optional hash of options for Q.Dialog.push and also:
-
[title='Confirm']
String optionalto override confirm dialog title.
-
[ok='OK']
String optionalto override confirm dialog 'Ok' button label, e.g. 'Yes'.
-
[cancel='Cancel']
String optionalto override confirm dialog 'Cancel' button label, e.g. 'No'.
-
[noClose=true]
Boolean optionalset to false to show a close button
-
[onClose]
Q.Event optionalOptional, occurs when dialog is closed
-
copy
-
[fields=null]
-
levels
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:
Returns:
Returns the shallow copy where some properties may have deepened the copy
currentScript
-
[stackLevels=0]
Gets information about the currently running script. Only works when called synchronously when the script loads.
Parameters:
-
[stackLevels=0]
Number optionalIf called within a function that was called inside a script, put 1, if deeper put 2, etc.
Returns:
object with properties "src", "path" and "file"
debounce
-
original
-
milliseconds
-
[immediate=false]
-
defaultValue
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
FunctionThe function to wrap
-
milliseconds
NumberThe number of milliseconds
-
[immediate=false]
Boolean optionalif true, the wrapper also lets the function be called without waiting if it hasn't been called for the given number of milliseconds.
-
defaultValue
MixedValue to return whenever original function isn't called
Returns:
The wrapper function
diff
-
container
-
container
-
[comparator]
Returns a container with the items in the first parameter that are not in the others
Parameters:
each
-
container,
-
callback
-
options
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 | Numberwhich can be an array, object or string. You can also pass up to three numbers here: from, to and optional step
-
callback
Function | StringA 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
ObjectCan include the following:
-
[ascending=false]
Boolean optionalpass true here to traverse in ascending key order, false in descending.
-
[numeric=false]
Boolean optionalused together with ascending. Pass true to use numeric sort instead of string sort.
-
[sort]
Function optionalpass 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 optionalset to true to skip properties found on the prototype chain.
-
ensure
-
property
-
loader
-
callback
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
MixedThe property to test for being undefined.
-
loader
String | Function | Q.EventSomething 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
FunctionThe 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
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
ObjectThis is the first object. It winds up being modified, and also returned as the return value of the function.
-
levels
NumberOptional. Precede any Object with an integer to indicate that we should also copy that many additional levels inside the object.
-
deep
Boolean | NumberOptional. Precede any Object with a boolean true to indicate that we should also copy the properties it inherits through its prototype chain.
-
anotherObject
ObjectPut as many objects here as you want, and they will extend the original one.
-
namespace
StringOptional namespace to use when extending encountered Q.Event objects
Returns:
The extended object.
find
-
elem
-
filter
-
callbackBefore
-
callbackAfter
-
options
-
shared
Finds all elements that contain a class matching the filter, and calls the callback for each of them.
Parameters:
-
elem
HTMLElement | ArrayAn element, or an array of elements, within which to search
-
filter
String | RegExp | True | NullThe name of the class or attribute to match
-
callbackBefore
FunctionA 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
FunctionA function to run when a match is found (after the children) If it returns false, the Q.find function stops searching.
-
options
ObjectAny options to pass to the callbacks as the second argument
-
shared
MixedAn optional object that will be passed to each callbackBefore and callbackAfter
first
-
container
-
options
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:
the value in the container, or undefined
firstErrorMessage
-
data
Try to find an error message assuming typical error data structures for the arguments
Parameters:
-
data
ObjectAn 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:
The first error message found, or null
firstKey
-
container
-
options
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:
formPost
-
action
-
[fields]
-
[method]
-
options
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 | HTMLElementThe form action. You can also pass an HTML form element here, and skip fields and method.
-
[fields]
Object optionalThe parameters of the form
-
[method]
String optionalThe method with which to submit the form. Defaults to the form's method, or "post" if missing.
-
options
Object | BooleanYou 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 optionalthe name of a window or iframe to use as the target.
-
[iframe]
HTMLElement optionalthe iframe to use. If not provided, this is filled to point to a newly created iframe object.
-
[onLoad]
Q.Event optionalcallback to call when results are loaded in the iframe. Ignored if options.target is specified.
-
[form]
HTMLElement optionalthe form to use. In this case, the action, fields and method are ignored.
-
getObject
-
name
-
[context=window]
-
[delimiter='.']
-
[create=undefined]
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 | ArrayPath 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 optionalOptional. Object to use as root of path. Null may be passed.
-
[delimiter='.']
String optionalThe delimiter to use in the name
-
[create=undefined]
Mixed optionalPass a value here to set with Q.setObject if nothing was there
Returns:
Returns the originally stored value, or undefined
if nothing is there
getter
-
original
-
[options={}]
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
FunctionThe 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 optionalAn optional hash of possible options, which include:
-
[prepare]
Function optionalThis 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 optionalan id to throttle on, or an Object that supports the throttle interface:
-
[throttleTry]
Function optionalfunction(subject, getter, args) - applies or throttles getter with subject, args
-
[throttleNext]
Function optionalfunction (subject) - applies next getter with subject
-
[throttleSize=100]
Integer optionalThe size of the throttle, if it is enabled
-
[cache]
Q.Cache | Boolean optionalpass false here to prevent caching, or an object which supports the Q.Cache interface
-
Returns:
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
Used for handling callbacks, whether they come as functions, strings referring to functions (if evaluated), arrays or hashes.
Parameters:
-
callables
MixedThe 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
FunctionYou can pass a function here if callables is a URL
-
context
ObjectThe context in which to call them
-
args
ArrayAn array of arguments to pass to them
-
options
ObjectIf callables is a url, these are the options to pass to Q.loadUrl, if any. Also can include:
-
[dontReload=false]
Boolean optionalif this is true and callback is a url matching current url, it is not reloaded
-
[loadUsingAjax=false]
Boolean optionalif this is true and callback is a url, it is loaded using Q.loadUrl
-
[externalLoader]
Function optionalwhen 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 optionaloptional fields to pass with any method other than "get"
-
[callback]
String | Function optionalif a string, adds a '&Q.callback='+encodeURIComponent(callback) to the querystring. If a function, this is the callback.
-
[loadExtras=true]
Boolean optionalif true, asks the server to load the extra scripts, stylesheets, etc. that are loaded on first page load
-
[target]
String optionalthe name of a window or iframe to use as the target. In this case callables is treated as a url.
-
[slotNames]
String | Array optionala comma-separated list of slot names, or an array of slot names
-
[quiet]
Boolean optionaldefaults to false. If true, allows visual indications that the request is going to take place.
-
Returns:
The number of handlers executed
init
-
options
Initialize the Q javascript platform
Parameters:
-
options
ObjectSupports the following options: "isLocalFile": defaults to false. Set this to true if you are calling Q.init from local file:/// context.
instanceOf
-
testing
-
Constructor
Use this instead of instanceof, it works with Q.mixin, even in IE
Parameters:
-
testing
Mixed -
Constructor
Function
interpolateUrl
-
url
-
[additional={}]
Interpolate some standard placeholders inside a url, such as {{AppName}} or {{PluginName}}
Returns:
The url with substitutions applied
isArray
-
value
Tests if the value is an array
Parameters:
-
value
MixedThe value to test
Returns:
Whether it is an array
isEmpty
-
o
Tests whether a variable contains a falsy value, or an empty object or array.
Parameters:
-
o
ObjectThe object to test.
Returns:
isInteger
-
value
-
[strictComparison=true]
Tests if the value is an integer
Parameters:
-
value
MixedThe value to test
-
[strictComparison=true]
Boolean optionalWhether to test strictly for a number
Returns:
Whether it is an integer
isPlainObject
-
x
Determines whether something is a plain object created within Javascript, or something else, like a DOMElement or Number
Parameters:
-
x
Mixed
Returns:
Returns true only for a non-null plain object
jsonRequest
-
fields
-
url
-
slotNames
-
callback
-
options
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
ObjectOptional object of fields to pass
-
url
StringThe URL you pass will normally be automatically extended through Q.ajaxExtend
-
slotNames
String | ArrayIf a string, expects a comma-separated list of slot names If an array, converts it to a comma-separated list
-
callback
FunctionThe JSON will be passed to this callback function
-
options
ObjectA hash of options, to be passed to Q.request
latest
-
key
-
ordinal
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.ToolRequests under the same key share the same incrementing ordinal
-
ordinal
Number | BooleanPass 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:
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
Loads a plugin
loadHandlebars
-
callback
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
FunctionThis function is called when the library is loaded
loadNonce
-
callback
-
context
-
args
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.
loadUrl
-
url
-
slotNames
-
callback
-
options
Parameters:
-
url
StringThe url to load.
-
slotNames
Array | StringOptional, defaults to all application slots
-
callback
FunctionCallback 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
ObjectOptional. An hash of options to pass to the loader, and can also include options for loadUrl itself:
-
[loader=Q.request]
Function optionalthe actual function to load the URL. See Q.request documentation for more options.
-
[handler]
Function optionalthe function to handle the returned data. Defaults to a function that fills the corresponding slot containers correctly.
-
[ignoreHistory=false]
Boolean optionalif true, does not push the url onto the history stack
-
[ignorePage=false]
Boolean optionalif 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 optionalIf true, ignores any errors in loading scripts.
-
[ignoreHash=false]
Boolean optionalif true, does not navigate to the hash part of the URL in browsers that can support it
-
[fields]
Object optionaladditional fields to pass via the querystring
-
[loadExtras=false]
Boolean optionalif true, asks the server to load the extra scripts, stylesheets, etc. that are loaded on first page load
-
[timeout=1500]
Number | Boolean optionalmilliseconds to wait for response, before showing cancel button and triggering onTimeout event, if any, passed to the options
-
[quiet=false]
Boolean optionalif true, allows visual indications that the request is going to take place.
-
[slotNames]
String | Array optionalan array of slot names to request and process (default is all slots in Q.info.slotNames)
-
[idPrefixes]
Array optionaloptional array of values to pass to PHP method Q_Html::pushIdPrefix for each slotName
-
[retainSlots]
Object optionalan object of {slotName: whetherToRetain} pairs, retained slots aren't requested
-
[slotContainer]
Boolean optionaloptional function taking (slotName, response) and returning the element, if any, to fill for that slot
-
[replaceElements]
Array optionalarray of elements or ids of elements in the document to replace. Overrides "data-q-retain" attributes but not retainSlots option.
-
[key='Q']
String optionalIf 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 optionalhandler to call when timeout is reached. Receives function as argument - the function might be called to cancel loading.
-
[onResponse]
Q.Event optionalhandler to call when the response comes back but before it is processed
-
[onError]
Q.Event optionalevent for when an error occurs, by default shows an alert
-
[onLoad]
Q.Event optionalevent which occurs when the parsed data comes back from the server
-
[onActivate]
Q.Event optionalevent which occurs when all Q.activate's processed and all script lines executed
-
[onLoadStart]
Q.Event optionalif "quiet" option is false, anything here will be called after the request is initiated.
-
[onLoadEnd]
Q.Event optionalif "quiet" option is false, anything here will be called after the request is fully completed.
-
Returns:
Returns a promise with an extra .cancel() method to cancel the action
milliseconds
-
sinceEpoch
Returns the number of milliseconds since the first call to this function i.e. since this script was parsed.
Parameters:
-
sinceEpoch
BooleanDefaults to false. If true, just returns the number of milliseconds in the UNIX timestamp.
Returns:
The number of milliseconds, with fractional part
milliseconds
-
sinceEpoch
Returns the number of milliseconds since the first call to this function (i.e. since script started).
Parameters:
-
sinceEpoch
BooleanDefaults to false. If true, just returns the number of milliseconds in the UNIX timestamp.
Returns:
The number of milliseconds, with fractional part
mixin
-
A
-
B
Mixes in one or more classes. Useful for inheritance and multiple inheritance.
Parameters:
-
A
FunctionThe 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
FunctionOne 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
Given an index and field values, returns the hostname and port for connecting to a Node.js server running Q
Parameters:
-
where
ObjectAn object of field: value pairs
Returns:
"scheme://hostname:port"
normalize
-
text
-
replacement
-
characters
-
numChars
-
[keepCaseIntact=false]
Normalizes text by converting it to lower case, and replacing all non-accepted characters with underscores.
Parameters:
-
text
StringThe text to normalize
-
replacement
StringDefaults to '_'. A string to replace one or more unacceptable characters. You can also change this default using the config Db/normalize/replacement
-
characters
StringDefaults 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
NumberThe maximum length of a normalized string. Default is 200.
-
[keepCaseIntact=false]
Boolean optionalIf true, doesn't convert to lowercase
Returns:
the normalized string
objectWithPrototype
-
original
Creates a copied object which you can extend, using existing object as prototype
Parameters:
-
original
Derived
Returns:
once
-
original
-
defaultValue
Wraps a function and returns a wrapper that will call the function at most once.
Parameters:
-
original
FunctionThe function to wrap
-
defaultValue
MixedValue to return whenever original function isn't called
Returns:
The wrapper function
page
-
page
-
handler
-
key
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
FunctionA 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
StringUse 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
Parses a querystring
Parameters:
Returns:
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
Wraps a function and causes it to return early if called recursively. Use sparingly, since most functions should make guarantees about postconditions.
Parameters:
Returns:
The wrapper function
promisify
-
getter
-
useSecondArgument
Takes a function and returns a version that returns a promise
Parameters:
Returns:
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]
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
Stringa value'] Optional, specifies text before input field useful to ask user to enter something (e.g. 'Enter your name').
-
callback:
FunctionThis 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 optionalAn optional hash of options for Q.Dialog.push and also:
-
[title='Prompt']
String optionalto override confirm dialog title.
-
[placeholder='']
String optionalto set a placeholder in the textbox
-
[maxlength=1000]
Number optionalthe maximum length of the input
-
[ok='OK']
String optionalto override confirm dialog 'Ok' button label, e.g. 'Yes'.
-
[cancel='Cancel']
String optionalto override confirm dialog 'Cancel' button label, e.g. 'No'.
-
[noClose=true]
Boolean optionalset to false to show a close button
-
[onClose]
Q.Event optionalOptional, occurs when dialog is closed
-
queryString
-
fields
-
keys
-
returnAsObject
Serialize a plain object, with possible sub-objects, into an http querystring.
Parameters:
-
fields
Object | String | HTMLElementThe 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
ArrayAn optional array of keys into the object, in the order to serialize things
-
returnAsObject
BooleanPass true here to get an object of {fieldname: value} instead of a string
queue
-
original
-
milliseconds
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:
Returns:
The wrapper function
ready
()
static
This is called when the DOM is ready
removeElement
-
element,
-
removeTools
Remove an element from the DOM and try to clean up memory as much as possible
Parameters:
-
element,
HTMLElement | Arrayor array of elements, or object of elements
-
removeTools
Booleanwhether to properly remove the tools before removing the element
removeEventListener
-
element
-
eventName
-
eventHandler
-
useCapture return
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
Replaces the contents of an element and does the right thing with all the tools in it
Parameters:
-
container
HTMLElementA 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 | StringAn HTML string or a Element which is not part of the DOM
-
options
ObjectOptional. A hash of options, including:
Returns:
Returns the container element if successful
req
-
uri
-
slotNames
-
callback
-
options
The easiest way to make direct web service requests in Q
Parameters:
-
uri
StringA string of the form "Module/action"
-
slotNames
String | ArrayIf a string, expects a comma-separated list of slot names. If an array, converts it to a comma-separated list.
-
callback
FunctionThe 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
ObjectA hash of options, to be passed to Q.request and Q.action (see their options).
Returns:
Object corresponding to the request
request
-
fields
-
url
-
slotNames
-
callback
-
options
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
ObjectOptional object of fields to pass
-
url
StringThe URL you pass will normally be automatically extended through Q.ajaxExtend
-
slotNames
String | ArrayIf a string, expects a comma-separated list of slot names If an array, converts it to a comma-separated list
-
callback
FunctionThe 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
ObjectA hash of options, including options that would be passed to Q.url(), but also these:
-
[method]
String optionalif set, adds a &Q.method= that value to the querystring, default "get"
-
[fields]
Object optionaloptional fields to pass with any method other than "get"
-
[form]
HTMLElement optionalif 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 optionalThe 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 optionaloptional array of Q_Html::pushIdPrefix values for each slotName
-
[skipNonce]
Boolean optionalif true, skips loading of the nonce
-
[xhr]
Object optionalset 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 optionalan optional function that takes the xhr object before the .send() is invoked on it
-
[parse]
Boolean optionalset to false to pass the unparsed string to the callback
-
[extend=true]
Boolean optionalif false, the URL is not extended with Q fields.
-
[query=false]
Boolean optionalif true simply returns the query url without issuing the request
-
[callbackName]
String optionalif 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 optionalyou can set it to false in order not to fetch the same url again
-
[quiet=true]
Boolean optionalthis option is just passed to your onLoadStart/onLoadEnd handlers in case they want to respect it.
-
[timestamp]
Boolean optionalwhether to include a timestamp (e.g. as a cache-breaker)
-
[onRedirect=Q.handle]
Function optionalif set and response data.redirect.url is not empty, automatically call this function.
-
[timeout=1500]
Boolean optionalmilliseconds to wait for response, before showing cancel button and triggering onTimeout event, if any, passed to the options
-
[onTimeout]
Q.Event optionalhandler to call when timeout is reached. First argument is a function which can be called to cancel loading.
-
[onResponse]
Q.Event optionalhandler to call when the response comes back but before it is processed
-
[onProcessed]
Q.Event optionalhandler to call when a response was processed
-
[onLoadStart]
Q.Event optionalif "quiet" option is false, anything here will be called after the request is initiated
-
[onLoadEnd]
Q.Event optionalif "quiet" option is false, anything here will be called after the request is fully completed
-
Returns:
Object corresponding to the request
require
-
src
-
callback
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.
setObject
-
name
-
value
-
[context=window]
-
[delimiter='.']
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:
Returns:
Returns the passed value if setting is successful or undefined
if not.
shuffle
-
arr
Shuffles an array
Parameters:
-
arr
ArrayThe array that gets passed here is shuffled in place
take
-
source
-
fields
Copies a subset of the fields in an object
Parameters:
Returns:
throttle
-
original
-
milliseconds
-
delayedFinal
-
defaultValue
Wraps a function and returns a wrapper that will call the function at most once every given milliseconds.
Parameters:
-
original
FunctionThe function to wrap
-
milliseconds
NumberThe number of milliseconds
-
delayedFinal
BooleanWhether the wrapper should execute the latest function call after throttle opens again, useful for e.g. following a mouse pointer that stopped.
-
defaultValue
MixedValue to return whenever original function isn't called
Returns:
The wrapper function
trigger
-
eventName
-
element
-
args
Triggers a method or Q.Event on all the tools inside a particular element, traversing in a depth-first manner.
Parameters:
-
eventName
StringRequired, the name of the method or Q.Event to trigger
-
element
HTMLElementOptional element to traverse from (defaults to document.body).
-
args
ArrayAny additional arguments that would be passed to the triggered method or event
url
-
what
-
fields
-
[options]
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 | NullUsually the stuff that comes after the base URL. If you don't provide this, then it just returns the Q.info.baseUrl
-
fields
ObjectOptional fields to append to the querystring. Fields containing null and undefined are skipped. NOTE: only handles scalar values in the object.
-
[options]
Object optionalA hash of options, including:
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.
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