Show:

Q Class

Module: Q

The main platform module. Contains basic properties and methods and serves as namespace for more specific sub-classes

Methods

assert

(
  • condition
  • complaint
)
static

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

Parameters:

batcher

(
  • batch
  • options
)
Function

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, 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 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.

copy

(
  • fields
  • 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 Array

    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

date

(
  • format
  • timestamp
)
String

Returns date/time string formatted the same way as PHP date function does

Parameters:

  • format String

    The format string

  • timestamp Number

    The date to format

Returns:

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

dir

(
  • start
  • [callback=null]
)

Search for directory and passes to callback if found. Passes an error if not directory

Parameters:

  • start String

    Directory path

  • [callback=null] Function optional

    Callback functions with arguments "error", "result" where result is an object {dirs: [...], files: [...]}

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 | 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

    ascending: 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
)
Object

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.

Returns:

Object:

The extended object.

first

(
  • container
  • options
)
Mixed

Returns the first non-undefined value found in a container

Parameters:

Returns:

Mixed:

the value in the container, or undefined

first

(
  • container
  • container
  • comparator
)
Array | Object

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

    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

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.nonEmptyKey]
)
Number | String

Returns the first key or index in a container with a value that's not undefined

Parameters:

Returns:

Number | String:

the index in the container, or null

getObject

(
  • name
  • [context=root]
  • [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"]

  • [context=root] 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

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
  • context
  • args
)
Number

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

Parameters:

  • callables Callable

    The callables to call

  • context Object

    The context in which to call them

  • args Array

    An array of arguments to pass to them

Returns:

Number:

The number of handlers executed

has

(
  • obj
  • key
)
Boolean static

Returns whether an object contains a property directly

Parameters:

Returns:

inherit

(
  • Base
  • Constructor
)
Function

Clones the Base constructor and mixes in the Constructor function

Parameters:

  • Base Function

    the base function, such as Q.Tool

  • Constructor Function

    the constructor function to change

Returns:

Function:

The resulting function to be used as a constructor

init

(
  • app
  • [notListen=false]
)

This should be called from Q.inc.js

Parameters:

  • app Object

    An object that MUST contain one key:

    • DIR Object

      the directory of the app

  • [notListen=false] Boolean optional

    Indicate wheather start http server. Useful for forking parallel processes.

instanceOf

(
  • testing
  • Constructor
)
static

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

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
)

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

Parameters:

  • o Mixed

    The object to test.

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

isPlainObject

() Boolean

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

Returns:

Boolean:

Returns true only for a non-null plain object

isSet

(
  • parent
  • keys
  • delimiter
)
Boolean

Walks the tree from the parent, and returns whether the path was defined

Parameters:

Returns:

latest

(
  • key
  • ordinal
)
Number | Boolean

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 was 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
});

listen

(
  • [options={}]
  • [callback=null]
)
static

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 optional

    Options can include:

    • [port] String optional

      the port to listen on

    • [host] String optional

      the hostname to listen on

    • [attach] Array optional

      an 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 optional

      To start an https server, pass options to https.createServer here, to override the ones in the "Q"/"node"/"https" config options, if any.

      • [key] String | Buffer optional
        Content of the private key file
      • [cert] String | Buffer optional
        Content of the certificate file
      • [ca] String | Buffer optional
        Content of the certificate authority file
      • [dhparam] String | Buffer optional
        Contains the DH parameters for Perfect Forward Secrecy
  • [callback=null] Function optional

    fired when the server actually starts listening. The callback receives server address as argument

log

(
  • message
  • [name]
  • [timestamp=true]
  • [callback=null]
)
Boolean

Writes a string to application log. If run outside Qbix application writes to console.

Parameters:

  • message Mixed

    The 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 optional

    If set log file will be named name+'_node.log', otherwise it would be named ('Q/app' config value) + '_node.log'

  • [timestamp=true] Boolean optional

    Whether to prepend the current timestamp

  • [callback=null] Function optional

    The callback to call after log file is written

Returns:

Boolean:

false if failed to parse arguments

makeEventEmitter

(
  • what
  • [isConstructor=false]
)

Makes an object into an event emitter.

Parameters:

  • what Object

    Can be an object or a function

  • [isConstructor=false] Boolean optional

    Whether the object is a constructor function. In this case, it is not the function that is made an emitter, but the objects which the function constructs.

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.

normalize

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

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
)
Object

Creates a derived object which you can extend, inheriting from an existing object

Parameters:

  • original Object

    The object to use as the prototype

Returns:

Object:

The derived object

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

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
)
String 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:

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

realPath

(
  • filename
  • [ignoreCache=false]
)
String | False

Check if a file exists in the include path And if it does, return the absolute path.

Parameters:

  • filename String

    Name of the file to look for

  • [ignoreCache=false] Boolean optional

    If true, then this function ignores the cached value, if any, and always attempts to search for the file. It will cache the new value.

Returns:

String | False:

The absolute path if file exists, false if it does not

require

(
  • what
)
Mixed

Require node module

Parameters:

Returns:

Mixed:

setObject

(
  • name
  • value
  • [context=root]
  • [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 Mixed

    value or object to place at location given by name

  • [context=root] 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 taht gets passed here is shuffled in place

take

(
  • source
  • An
)
Object static

Copies a subset of the fields in an object

Parameters:

  • source Object

    An Object from which to take things

  • An Array | Object

    array of fields to take or an object of fieldname: default pairs

Returns:

Object:

a new Object

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

time

(
  • handle
)

Start time counter

Parameters:

  • handle String

    A handle to refer to time counter. Shall be namespaced to avoid overlap with other possible counters - Q/PROCESS/NAME

timeEnd

(
  • handle
)
String | Null

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 String

    The handle started with Q.time(). If not started returns null

Returns:

String | Null:

typeOf

(
  • value
)
String

Returns the type of a value

Parameters:

  • value Mixed

    The value to test type

Returns:

String:

String description of the type

url

(
  • what
  • fields
  • [options]
)

Obtain a URL

Parameters:

  • what Object

    Usually the stuff that comes after the base URL

  • 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

view

(
  • viewName
  • [params=[]]
  • [options=[]]
)
String

Renders a particular view

Parameters:

  • viewName String

    The full name of the view

  • [params=[]] Array optional

    Parameters to pass to the view

  • [options=[]] Array optional

    Some options

    • [language=null] String | Null optional

      Preferred language

    • [source=false] String | Null optional

Returns:

String:

The rendered content of the view

Properties

app

Object

App data for your scripts

Bootstrap

Object

Reference to Q.Bootstrap class

CLASSES_DIR

String

Directory for platform classes. Also Q.app.CLASSES_DIR is defined for application classes

Config

Object

Reference to Q.Config class

CONFIG_DIR

String

Directory for platform config. Also Q.app.CONFIG_DIR is defined for application config

Crypto

Object

Reference to Q.Crypto class

Dispatcher

Object

Reference to Q.Dispatcher class

DS

String

Directory separator

Exception

Object

Reference to Q.Exception class

FILES_DIR

String

Directory for platform files. Also Q.app.FILES_DIR is defined for application files

Handlebars

Object

Reference to Q.Handlebars class

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

PS

String

Path separator

Request

Object

Reference to Q.Request class

SCRIPTS_DIR

String

Directory for platform scripts. Also Q.app.SCRIPTS_DIR is defined for application scripts

Socket

Object

Reference to Q.Socket class

TESTS_DIR

String

Directory for platform test dir. Also Q.app.TESTS_DIR is defined for application test dir

Text

Object

Reference to Q.Text class

Tree

Object

Reference to Q.Tree class

Utils

Object

Reference to Q.Utils class

VIEWS_DIR

String

Directory for platform views. Also Q.app.VIEWS_DIR is defined for application views

Events

init

Qbix platform initialized

Event Payload:

  • Q Q

    Initialized Qbix instance

request

Http request

Event Payload:

  • req http.Request

    The request object

  • res http.Response

    The response object