Q Class
The main platform module. Contains basic properties and methods and serves as namespace for more specific sub-classes
Item Index
Methods
- assert static
- batcher
- copy static
- date
- debounce static
- dir
- each
- exceptionHandler
- extend
- first
- first
- firstErrorMessage static
- firstKey
- getObject static
- getter
- handle
- has static
- inherit
- init
- instanceOf static
- interpolateUrl static
- isArray static
- isEmpty
- isInteger static
- isPlainObject
- isSet
- latest
- listen static
- log
- makeEventEmitter
- milliseconds
- milliseconds static
- mixin static
- normalize
- objectWithPrototype
- once static
- pipe
- pluginBaseUrl
- queryString static
- queue static
- realPath
- require
- setObject static
- shuffle static
- take static
- throttle static
- time
- timeEnd
- typeOf
- url
- view
Properties
Methods
assert
-
condition
-
complaint
Throws Q.Error with complaint if condition evaluates to something falsy
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, params 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.
copy
-
fields
-
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
date
-
format
-
timestamp
Returns date/time string formatted the same way as PHP date function does
Returns:
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
dir
-
start
-
[callback=null]
Search for directory and passes to callback if found. Passes an error if not directory
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
Objectascending: Optional. Pass true here to traverse in ascending key order, false in descending. numeric: Optional. Used together with ascending. Use numeric sort instead of string sort. sort: Optional. Pass a compare Function here to be used when sorting object keys before traversal. Also can pass a String naming the property on which to sort. hasOwnProperty: Optional. Set to true to skip properties found on the prototype chain.
exceptionHandler
-
exception
Default exception handler for Q
Parameters:
-
exception
Exception
extend
-
target
-
levels
-
deep
-
anotherObject
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.
Returns:
The extended object.
first
-
container
-
options
Returns the first non-undefined value found in a container
Parameters:
Returns:
the value in the container, or undefined
first
-
container
-
container
-
comparator
Returns a container with the items in the first parameter that are not in the others
Parameters:
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.nonEmptyKey]
Returns the first key or index in a container with a value that's not undefined
Parameters:
getObject
-
name
-
[context=root]
-
[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"]
-
[context=root]
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
-
context
-
args
Used for handling callbacks, whether they come as functions, strings referring to functions (if evaluated), arrays or hashes.
Parameters:
Returns:
The number of handlers executed
inherit
-
Base
-
Constructor
Clones the Base constructor and mixes in the Constructor function
Parameters:
Returns:
The resulting function to be used as a constructor
init
-
app
-
[notListen=false]
This should be called from Q.inc.js
instanceOf
-
testing
-
Constructor
Use this instead of instanceof, it works with Q.mixin
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
MixedThe object to test.
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
()
Boolean
Determines whether something is a plain object created within Javascript, or something else, like a DOMElement or Number
Returns:
Returns true only for a non-null plain object
isSet
-
parent
-
keys
-
delimiter
Walks the tree from the parent, and returns whether the path was defined
Returns:
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
});
listen
-
[options={}]
-
[callback=null]
Starts internal server to listen for messages from PHP processes and other things. Uses the Q/node/port and Q/node/host config fields. Make sure to protect the communication using a firewall.
Parameters:
-
[options={}]
Object optionalOptions can include:
-
[port]
String optionalthe port to listen on
-
[host]
String optionalthe hostname to listen on
-
[attach]
Array optionalan array of additional listeners to attach. Each member is a name of a class (e.g. "Q.Socket", "Q.Dispatcher" and "Db") which has the listen(options) method.
-
[https]
Object optionalTo start an https server, pass options to https.createServer here, to override the ones in the "Q"/"node"/"https" config options, if any.
-
-
[callback=null]
Function optionalfired when the server actually starts listening. The callback receives server address as argument
log
-
message
-
[name]
-
[timestamp=true]
-
[callback=null]
Writes a string to application log. If run outside Qbix application writes to console.
Parameters:
-
message
MixedThe data to write to log file. If data is string it is written to log, if it has other type it is converted to string using util.format with depth defined by Q/var_dump_max_levels config key
-
[name]
String optionalIf set log file will be named name+'_node.log', otherwise it would be named ('Q/app' config value) + '_node.log'
-
[timestamp=true]
Boolean optionalWhether to prepend the current timestamp
-
[callback=null]
Function optionalThe callback to call after log file is written
Returns:
false if failed to parse arguments
makeEventEmitter
-
what
-
[isConstructor=false]
Makes an object into an event emitter.
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.
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 derived object which you can extend, inheriting from an existing object
Parameters:
-
original
ObjectThe object to use as the prototype
Returns:
The derived object
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
pipe
()
Q.Pipe
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
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
Returns:
A querystring that can be used with HTTP requests
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
realPath
-
filename
-
[ignoreCache=false]
Check if a file exists in the include path And if it does, return the absolute path.
Parameters:
Returns:
The absolute path if file exists, false if it does not
setObject
-
name
-
value
-
[context=root]
-
[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 taht gets passed here is shuffled in place
take
-
source
-
An
Copies a subset of the fields in an object
Parameters:
Returns:
a new Object
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
time
-
handle
Start time counter
Parameters:
-
handle
StringA handle to refer to time counter. Shall be namespaced to avoid overlap with other possible counters - Q/PROCESS/NAME
timeEnd
-
handle
Retrieves time difference between start by Q.time() and current time.
Time is formatted string "XX days XX hours XX minutes XX seconds"
If time is less than a second returns "XXX milliseconds"
Parameters:
-
handle
StringThe handle started with Q.time(). If not started returns null
Returns:
typeOf
-
value
Returns the type of a value
Parameters:
-
value
MixedThe value to test type
Returns:
String description of the type
url
-
what
-
fields
-
[options]
Obtain a URL
Properties
CLASSES_DIR
String
Directory for platform classes. Also Q.app.CLASSES_DIR is defined for application classes
CONFIG_DIR
String
Directory for platform config. Also Q.app.CONFIG_DIR is defined for application config
FILES_DIR
String
Directory for platform files. Also Q.app.FILES_DIR is defined for application files
HANDLERS_DIR
String
Directory for platform handlers. Also Q.app.HANDLERS_DIR is defined for application handlers
LOCAL_DIR
String
Directory for platform local config. Also Q.app.LOCAL_DIR is defined for application local config
PLUGINS_DIR
String
Directory for platform plugins. Also Q.app.PLUGINS_DIR is defined for application plugins
SCRIPTS_DIR
String
Directory for platform scripts. Also Q.app.SCRIPTS_DIR is defined for application scripts
TESTS_DIR
String
Directory for platform test dir. Also Q.app.TESTS_DIR is defined for application test dir
VIEWS_DIR
String
Directory for platform views. Also Q.app.VIEWS_DIR is defined for application views
Events
request
Http request
Event Payload:
-
req
http.RequestThe request object
-
res
http.ResponseThe response object