Properties
Adds dojo.fx animation support to dojo.query()
Adds a chainable html method to dojo.query() / Nodelist instances for setting/replacing node content
Adds a chainable methods to dojo.query() / Nodelist instances for manipulating HTML
and DOM nodes and their properties.
Adds a chainable methods to dojo.query() / Nodelist instances for traversing the DOM
dojo._global_omit_module_check dojo._xdDebugScopeChecked dojo._xdRealRequireLocalization The root relative path to dojo.js (as a string)
True if the client is a web-browser
| undefined
Version as a Number if client is Chrome browser. undefined otherwise.
isMac: Boolean
True if the client runs on Mac
| undefined
Version as a Number if client is FireFox. undefined otherwise. Corresponds to
major detected FireFox version (1.5, 2, 3, etc.)
| undefined
Version as a Number if client is MSIE(PC). undefined otherwise. Corresponds to
major detected IE version (6, 7, 8, etc.)
| undefined
Version as a Number if client is a KHTML browser. undefined otherwise. Corresponds to major
detected version.
| undefined
Version as a Number if client is a Mozilla-based browser (Firefox,
SeaMonkey). undefined otherwise. Corresponds to major detected version.
| undefined
Version as a Number if client is Opera. undefined otherwise. Corresponds to
major detected version.
| undefined
Version as a Number if client is Safari or iPhone. undefined otherwise.
| undefined
Version as a Number if client is a WebKit-derived browser (Konqueror,
Safari, Chrome, etc.). undefined otherwise.
the locale as defined by Dojo (read-only)
D.O.H. Test files for Dojo unit testing.
Methods
| Parameter | Type | Description |
|---|
| kwArgs | | |
Returns Handle
| Parameter | Type | Description |
|---|
| obj | | |
| event | | |
| context | | |
| method | | |
| dontFix | | |
The default easing function for dojo.Animation(s)
| Parameter | Type | Description |
|---|
| n | Decimal | Optional. |
Existing alias for dojo.destroy. Deprecated, will be removed
in 2.0
| Parameter | Type | Description |
|---|
| node | | |
| Parameter | Type | Description |
|---|
| obj | | |
| event | | |
| handle | | |
| listener | | |
Adds escape sequences for non-visual characters, double quote and
backslash and surrounds with double quotes to form a valid string
literal.
| Parameter | Type | Description |
|---|
| str | String | |
Returns dojo.Animation
Returns an animation that will fade the node defined by
args.node from the start to end values passed (args.start
args.end) (end is mandatory, start is optional)
| Parameter | Type | Description |
|---|
| args | Object | |
| Parameter | Type | Description |
|---|
| nodeList | | |
| simpleFilter | | |
dojo._fixIeBiDiScrollLeft Returns Integer
| Parameter | Type | Description |
|---|
| scrollLeft | Integer | |
| Parameter | Type | Description |
|---|
| node | | |
| computedStyle | | |
- l/t = the sum of left/top border (respectively)
- w = the sum of the left and right border
- h = the sum of the top and bottom border
The w/h are used for calculating boxes.
Normally application code will not need to invoke this
directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
|---|
| n | DomNode | |
| computedStyle | Object | |
Returns an object that encodes the width, height, left and top
positions of the node's content box, irrespective of the
current box model.
| Parameter | Type | Description |
|---|
| node | | |
| computedStyle | | |
dojo._getIeDocumentElementOffset The following values in IE contain an offset:
event.clientX
event.clientY
node.getBoundingClientRect().left
node.getBoundingClientRect().top
But other position related values do not contain this offset,
such as node.offsetLeft, node.offsetTop, node.style.left and
node.style.top. The offset is always (2, 2) in LTR direction.
When the body is in RTL direction, the offset counts the width
of left scroll bar's width. This function computes the actual
offset.
returns an object that encodes the width, height, left and top
positions of the node's margin box.
| Parameter | Type | Description |
|---|
| node | DomNode | |
| computedStyle | Object | |
returns object with properties useful for box fitting with
regards to box margins (i.e., the outer-box).
* l/t = marginLeft, marginTop, respectively
* w = total width, margin inclusive
* h = total height, margin inclusive
The w/h are used for calculating boxes.
Normally application code will not need to invoke this
directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
|---|
| n | | |
| computedStyle | | |
Returns String
gets the prefix associated with module
| Parameter | Type | Description |
|---|
| module | String | |
Returns Array
Converts a module name in dotted JS notation to an array
representing the path in the source tree
| Parameter | Type | Description |
|---|
| modulename | String | |
Returns Number: Number between 0 and 1
Returns the current opacity of the passed node as a
floating-point value between 0 and 1.
| Parameter | Type | Description |
|---|
| node | DomNode | a reference to a DOM node. Does NOT support taking an
ID string for speed reasons. |
dojo._getPadBorderExtents
- l/t = the sum of left/top padding and left/top border (respectively)
- w = the sum of the left and right padding and border
- h = the sum of the top and bottom padding and border
The w/h are used for calculating boxes.
Normally application code will not need to invoke this
directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
|---|
| n | DomNode | |
| computedStyle | Object | |
Returns an object with w, h, l, t properties:
l/t = left/top padding (respectively)
w = the total of the left and right padding
h = the total of the top and bottom padding
If 'node' has position, l/t forms the origin for child nodes.
The w/h are used for calculating boxes.
Normally application code will not need to invoke this
directly, and will use the ...box... functions instead.
| Parameter | Type | Description |
|---|
| n | DomNode | |
| computedStyle | Object | |
Returns mixed
| Parameter | Type | Description |
|---|
| parts | Array | |
| create | Boolean | |
| context | Object | |
Returns null|String: The response text. null is returned when there is a
failure and failure is okay (an exception otherwise)
Read the contents of the specified uri and return those contents.
| Parameter | Type | Description |
|---|
| uri | URI | A relative or absolute uri. |
| fail_ok | Boolean | Default false. If fail_ok and loading fails, return null
instead of throwing. |
Returns mixed
| Parameter | Type | Description |
|---|
| scope | | |
| method | , | One or more can be passed. |
| Parameter | Type | Description |
|---|
| args | | |
| sender | | |
| Parameter | Type | Description |
|---|
| g | | |
| d | | |
| f | | |
Adds query params discovered by the io deferred construction to the URL.
Only use this for operations which are fundamentally GET-type operations.
| Parameter | Type | Description |
|---|
| ioArgs | dojo.__IoCallbackArgs | | Parameter | Type | Description |
|---|
| args | Object | the original object argument to the IO call.
| | xhr | XMLHttpRequest | For XMLHttpRequest calls only, the
XMLHttpRequest object that was used for the
request.
| | url | String | The final URL used for the call. Many times it
will be different than the original args.url
value.
| | query | String | For non-GET requests, the
name1=value1&name2=value2 parameters sent up in
the request.
| | handleAs | String | The final indicator on how the response will be
handled.
| | id | String | For dojo.io.script calls only, the internal
script ID used for the request.
| | canDelete | Boolean | For dojo.io.script calls only, indicates
whether the script tag that represents the
request can be deleted after callbacks have
been called. Used internally to know when
cleanup can happen on JSONP-type requests.
| | json | Object | For dojo.io.script calls only: holds the JSON
response for JSONP-type requests. Used
internally to hold on to the JSON responses.
You should not need to access it directly --
the same object should be passed to the success
callbacks directly.
|
|
Cancels all pending IO requests, regardless of IO type
(xhr, script, iframe).
Used by IO transports. An IO transport should
call this method before making the network connection.
| Parameter | Type | Description |
|---|
| dfd | Deferred | |
sets up the Deferred and ioArgs property on the Deferred so it
can be used in an io call.
| Parameter | Type | Description |
|---|
| args | dojo.__IoArgs | The args object passed into the public io call. Recognized properties on
the args object are:| Parameter | Type | Description |
|---|
| url | String | URL to server endpoint.
| | content | Object | Contains properties with string values. These
properties will be serialized as name1=value2 and
passed in the request.
| | timeout | Integer | Milliseconds to wait for the response. If this time
passes, the then error callbacks are called.
| | form | DOMNode | DOM node for a form. Used to extract the form values
and send to the server.
| | preventCache | Boolean | Default is false. If true, then a
"dojo.preventCache" parameter is sent in the request
with a value that changes with each request
(timestamp). Useful only with GET-type requests.
| | handleAs | String | Acceptable values depend on the type of IO
transport (see specific IO calls for more information).
rawBody: String?
Sets the raw body for an HTTP request. If this is used, then the content
property is ignored. This is mostly useful for HTTP methods that have
a body to their requests, like PUT or POST. This property can be used instead
of postData and putData for dojo.rawXhrPost and dojo.rawXhrPut respectively.
| | ioPublish | Boolean | Set this explicitly to false to prevent publishing of topics related to
IO operations. Otherwise, if djConfig.ioPublish is set to true, topics
will be published via dojo.publish for different phases of an IO operation.
See dojo.__IoPublish for a list of topics that are published.
|
|
| canceller | Function | The canceller function used for the Deferred object. The function
will receive one argument, the Deferred object that is related to the
canceller. |
| okHandler | Function | The first OK callback to be registered with Deferred. It has the opportunity
to transform the OK response. It will receive one argument -- the Deferred
object returned from this function. |
| errHandler | Function | The first error callback to be registered with Deferred. It has the opportunity
to do cleanup on an error. It will receive two arguments: error (the
Error object) and dfd, the Deferred object returned from this function. |
Watches the io request represented by dfd to see if it completes.
| Parameter | Type | Description |
|---|
| dfd | Deferred | The Deferred object to watch. |
| validCheck | Function | Function used to check if the IO request is still valid. Gets the dfd
object as its only argument. |
| ioCheck | Function | Function used to check if basic IO call worked. Gets the dfd
object as its only argument. |
| resHandle | Function | Function used to process response. Gets the dfd
object as its only argument. |
True if the node is BUTTON or INPUT.type="button".
| Parameter | Type | Description |
|---|
| node | DomNode | |
Returns Boolean
| Parameter | Type | Description |
|---|
| http | | |
determines if URI is local or not.
| Parameter | Type | Description |
|---|
| uri | String | |
| Parameter | Type | Description |
|---|
| e | | |
Returns Boolean
Loads and interprets the script located at relpath, which is
relative to the script root directory. If the script is found but
its interpretation causes a runtime exception, that exception is
not caught by us, so the caller will see it. We return a true
value if and only if the script is found.
| Parameter | Type | Description |
|---|
| relpath | String | A relative path to a script (no leading '/', and typically ending
in '.js'). |
| module | String | Optional. A module whose existance to check for after loading a path. Can be
used to determine success or failure of the load. |
| cb | Function | Optional. a callback function to pass the result of evaluating the script |
Returns Boolean|Boolean: contents? true : false
Wanted to override getText(), but it is used by
the widget code in too many, synchronous ways right now.
| Parameter | Type | Description |
|---|
| uri | String | a uri which points at the script to be loaded |
| cb | Function | a callback function to process the result of evaluating the script
as an expression, typically used by the resource bundle loader to
load JSON-style resources |
| currentIsXDomain | boolean | |
| module | String | |
Returns Boolean
calls loadUri then findModule and returns true if both succeed
| Parameter | Type | Description |
|---|
| uri | String | |
| moduleName | String | |
| cb | Function | Optional. |
Returns Object
Adds all properties and methods of source to target. This addition
is "prototype extension safe", so that instances of objects
will not pass along prototype defaults.
| Parameter | Type | Description |
|---|
| target | Object | |
| source | Object | |
Returns Boolean
checks to see if module has been established
| Parameter | Type | Description |
|---|
| module | String | |
sets width/height/left/top in the current (native) box-model
dimentions. Uses the unit passed in u.
| Parameter | Type | Description |
|---|
| node | DomNode | DOM Node reference. Id string not supported for performance
reasons. |
| l | Number | Optional. left offset from parent. |
| t | Number | Optional. top offset from parent. |
| w | Number | Optional. width in current box model. |
| h | Number | Optional. width in current box model. |
| u | String | Optional. unit measure to use for other measures. Defaults to "px". |
Sets the size of the node's contents, irrespective of margins,
padding, or borders.
| Parameter | Type | Description |
|---|
| node | DomNode | |
| widthPx | Number | |
| heightPx | Number | |
| computedStyle | Object | |
sets the size of the node's margin box and placement
(left/top), irrespective of box model. Think of it as a
passthrough to dojo._setBox that handles box-model vagaries for
you.
| Parameter | Type | Description |
|---|
| node | DomNode | |
| leftPx | Number | Optional. |
| topPx | Number | Optional. |
| widthPx | Number | Optional. |
| heightPx | Number | Optional. |
| computedStyle | Object | |
Returns Number: Number between 0 and 1
set the opacity of the passed node portably. Returns the
new opacity of the node.
| Parameter | Type | Description |
|---|
| node | DOMNode | a reference to a DOM node. Does NOT support taking an
ID string for performance reasons. |
| opacity | Number | A Number between 0 and 1. 0 specifies transparent. |
dojo._spidermonkeyCurrentFile | Parameter | Type | Description |
|---|
| depth | | |
Converts an array-like object (i.e. arguments, DOMCollection) to an
array. Returns a new Array with the elements of obj.
| Parameter | Type | Description |
|---|
| obj | Object | the object to "arrayify". We expect the object to have, at a
minimum, a length property which corresponds to integer-indexed
properties. |
| offset | Number | Optional. the location in obj to start iterating from. Defaults to 0.
Optional. |
| startWith | Array | Optional. An array to pack with the properties of obj. If provided,
properties in obj are appended at the end of startWith and
startWith is the returned array. |
Returns DOMNode: DocumentFragment
converts HTML string into DOM nodes.
| Parameter | Type | Description |
|---|
| frag | String | the HTML fragment |
| doc | DocumentNode | Optional. optional document to use when creating DOM nodes, defaults to
dojo.doc if not specified. |
Example 1
Create a table row:
var tr = dojo._toDom("<tr><td>First!</td></tr>");
| Parameter | Type | Description |
|---|
| element | | |
| value | | |
| avalue | | |
Returns boolean
True if the node uses border-box layout.
| Parameter | Type | Description |
|---|
| node | DomNode | |
Internal xd loader function.
Clears the interval timer used to check on the
status of in-flight xd module resource requests.
Returns String
Internal xd loader function. Creates an xd module source given an
non-xd module contents.
| Parameter | Type | Description |
|---|
| contents | String | |
| resourceName | String | |
| resourcePath | String | |
| Parameter | Type | Description |
|---|
| resourceName | | |
Internal xd loader function.
Does a depth first, breadth second search and eval of required modules.
| Parameter | Type | Description |
|---|
| reqChain | Array | |
| Parameter | Type | Description |
|---|
| fileContents | String | |
Figure out whether the path is local or x-domain
If there is a colon before the first / then, we have a URL with a protocol.
| Parameter | Type | Description |
|---|
| relpath | string | |
dojo._xdLoadFlattenedBundle Internal xd loader function. Used when loading
a flattened localized bundle via a script tag.
| Parameter | Type | Description |
|---|
| moduleName | String | |
| bundleName | String | |
| locale | String | Optional. |
| bundleData | Object | |
Internal xd loader function. Resets the xd state.
Internal xd loader function. Called by an xd module resource when
it has been loaded via a script tag.
| Parameter | Type | Description |
|---|
| res | Object | |
Returns Object
Internal xd loader function. Determines what to do with a dependency
that was listed in an xd version of a module contents.
| Parameter | Type | Description |
|---|
| dep | Array | |
Internal xd loader function.
Walks the requires and evaluates module resource contents in
the right order.
Internal xd loader function.
Monitors in-flight requests for xd module resources.
| Parameter | Type | Description |
|---|
| args | | |
Adds the specified classes to the end of the class list on the
passed node. Will not re-apply duplicate classes.
| Parameter | Type | Description |
|---|
| node | DomNode|String | String ID or DomNode reference to add a class string too |
| classStr | String|Array | A String class name to add, or several space-separated class names,
or an array of class names. |
Example 1
Add a class to some node:
dojo.addClass("someNode", "anewClass");
Example 2
Add two classes at once:
dojo.addClass("someNode", "firstClass secondClass");
Example 3
Add two classes at once (using array):
dojo.addClass("someNode", ["firstClass", "secondClass"]);
Example 4
Available in `dojo.NodeList` for multiple additions
dojo.query("ul > li").addClass("firstLevel");
Registers a function to be triggered after the DOM has finished
loading and dojo.require modules have loaded. Widgets declared in markup
have been instantiated if djConfig.parseOnLoad is true when this fires.
Images and CSS files may or may not have finished downloading when
the specified function is called. (Note that widgets' CSS and HTML
code is guaranteed to be downloaded before said widgets are
instantiated, though including css resouces BEFORE any script elements
is highly recommended).
| Parameter | Type | Description |
|---|
| obj | Object | |
| functionName | String|Function | Optional. |
Example 1
Register an anonymous function to run when everything is ready
dojo.addOnLoad(function(){ doStuff(); });
Example 2
Register a function to run when everything is ready by pointer:
var init = function(){ doStuff(); }
dojo.addOnLoad(init);
Example 3
Register a function to run scoped to `object`, either by name or anonymously:
dojo.addOnLoad(object, "functionName");
dojo.addOnLoad(object, function(){ doStuff(); });
registers a function to be triggered when window.onunload fires.
Be careful trying to modify the DOM or access JavaScript properties
during this phase of page unloading: they may not always be available.
Consider dojo.addOnUnload() if you need to modify the DOM or do heavy
JavaScript work.
| Parameter | Type | Description |
|---|
| obj | Object | Optional. |
| functionName | String|Function | Optional. |
Example 1
dojo.addOnWindowUnload(functionPointer)
dojo.addOnWindowUnload(object, "functionName")
dojo.addOnWindowUnload(object, function(){ /* ... */});
Returns dojo.Animation
dojo.anim is a simpler (but somewhat less powerful) version
of dojo.animateProperty. It uses defaults for many basic properties
and allows for positional parameters to be used in place of the
packed "property bag" which is used for other Dojo animation
methods.
The dojo.Animation object returned from dojo.anim will be
already playing when it is returned from this function, so
calling play() on it again is (usually) a no-op.
| Parameter | Type | Description |
|---|
| node | DOMNode|String | a DOM node or the id of a node to animate CSS properties on |
| properties | Object | |
| duration | Integer | Optional. The number of milliseconds over which the animation
should run. Defaults to the global animation default duration
(350ms). |
| easing | Function | Optional. An easing function over which to calculate acceleration
and deceleration of the animation through its duration.
A default easing algorithm is provided, but you may
plug in any you wish. A large selection of easing algorithms
are available in dojo.fx.easing. |
| onEnd | Function | Optional. A function to be called when the animation finishes
running. |
| delay | Integer | Optional. The number of milliseconds to delay beginning the
animation by. The default is 0. |
Example 1
Fade out a node
dojo.anim("id", { opacity: 0 });
Example 2
Fade out a node over a full second
dojo.anim("id", { opacity: 0 }, 1000);
Returns dojo.Animation
The standard animation doesn't know what to do with something like
rect(...). This class identifies complex properties by they being a
string and having parenthesis. If so, that property is made into a
dojox.fx._Complex object and the getValue() is obtained from
there.
| Parameter | Type | Description |
|---|
| args | dojo.__AnimArgs | | Parameter | Type | Description |
|---|
| properties | Object | |
|
Example 1
A simple animation that changes the width of the specified node.
dojo.animateProperty({
node: "nodeId",
properties: { width: 400 },
}).play();
Dojo figures out the start value for the width and converts the
integer specified for the width to the more expressive but
verbose form `{ width: { end: '400', units: 'px' } }` which you
can also specify directly. Defaults to 'px' if ommitted.
Example 2
Animate width, height, and padding over 2 seconds... the
pedantic way:
dojo.animateProperty({ node: node, duration:2000,
properties: {
width: { start: '200', end: '400', units:"px" },
height: { start:'200', end: '400', units:"px" },
paddingTop: { start:'5', end:'50', units:"px" }
}
}).play();
Note 'paddingTop' is used over 'padding-top'. Multi-name CSS properties
are written using "mixed case", as the hyphen is illegal as an object key.
Example 3
Plug in a different easing function and register a callback for
when the animation ends. Easing functions accept values between
zero and one and return a value on that basis. In this case, an
exponential-in curve.
dojo.animateProperty({
node: "nodeId",
// dojo figures out the start value
properties: { width: { end: 400 } },
easing: function(n){
return (n==0) ? 0 : Math.pow(2, 10 * (n - 1));
},
onEnd: function(node){
// called when the animation finishes. The animation
// target is passed to this function
}
}).play(500); // delay playing half a second
Example 4
Like all `dojo.Animation`s, animateProperty returns a handle to the
Animation instance, which fires the events common to Dojo FX. Use `dojo.connect`
to access these events outside of the Animation definiton:
var anim = dojo.animateProperty({
node:"someId",
properties:{
width:400, height:500
}
});
dojo.connect(anim,"onEnd", function(){
console.log("animation ended");
});
// play the animation now:
anim.play();
Example 5
Each property can be a function whose return value is substituted along.
Additionally, each measurement (eg: start, end) can be a function. The node
reference is passed direcly to callbacks.
dojo.animateProperty({
node:"mine",
properties:{
height:function(node){
// shrink this node by 50%
return dojo.position(node).h / 2
},
width:{
start:function(node){ return 100; },
end:function(node){ return 200; }
}
}
}).play();
Example 6
var ani = dojo.animateProperty({
node:dojo.byId("myDiv"),
duration:600,
properties:{
clip:{start:'rect(0px 50px 50px 0px)', end:'rect(10px 30px 30px 10px)'}
}
}).play();
Returns DomNode|Anything: when used as a getter, the value of the requested attribute
or null if that attribute does not have a specified or
default value;
when used as a setter, the DOM node
Handles normalized getting and setting of attributes on DOM
Nodes. If 2 arguments are passed, and a the second argumnt is a
string, acts as a getter.
If a third argument is passed, or if the second argument is a
map of attributes, acts as a setter.
When passing functions as values, note that they will not be
directly assigned to slots on the node, but rather the default
behavior will be removed and the new behavior will be added
using dojo.connect(), meaning that event handler properties
will be normalized and that some caveats with regards to
non-standard behaviors for onsubmit apply. Namely that you
should cancel form submission using dojo.stopEvent() on the
passed event object instead of returning a boolean value from
the handler itself.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to the element to get or set the attribute on |
| name | String|Object | the name of the attribute to get or set. |
| value | String | Optional. The value to set for the attribute |
Example 1
// get the current value of the "foo" attribute on a node
dojo.attr(dojo.byId("nodeId"), "foo");
// or we can just pass the id:
dojo.attr("nodeId", "foo");
Example 2
// use attr() to set the tab index
dojo.attr("nodeId", "tabIndex", 3);
Example 3
Set multiple values at once, including event handlers:
dojo.attr("formId", {
"foo": "bar",
"tabIndex": -1,
"method": "POST",
"onsubmit": function(e){
// stop submitting the form. Note that the IE behavior
// of returning true or false will have no effect here
// since our handler is connect()ed to the built-in
// onsubmit behavior and so we need to use
// dojo.stopEvent() to ensure that the submission
// doesn't proceed.
dojo.stopEvent(e);
// submit the form with Ajax
dojo.xhrPost({ form: "formId" });
}
});
Example 4
Style is s special case: Only set with an object hash of styles
dojo.attr("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
Example 5
Again, only set style as an object hash of styles:
var obj = { color:"#fff", backgroundColor:"#000" };
dojo.attr("someNode", "style", obj);
// though shorter to use `dojo.style()` in this case:
dojo.style("someNode", obj);
Returns dojo.Color
Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend,
can reuse a previously allocated dojo.Color object for the result
| Parameter | Type | Description |
|---|
| start | dojo.Color | |
| end | dojo.Color | |
| weight | Number | |
| obj | dojo.Color | Optional. |
Returns Node
Return the body element of the document
return the body object associated with dojo.doc
Example 1
dojo.body().appendChild(dojo.doc.createElement('div'));
Returns assume it's a node|DomNode
Returns DOM node with matching id attribute or null
if not found. If id is a DomNode, this function is a no-op.
| Parameter | Type | Description |
|---|
| id | String|DOMNode | A string to match an HTML id attribute or a reference to a DOM Node |
| doc | Document | Document to work in. Defaults to the current value of
dojo.doc. Can be used to retrieve
node references from other documents. |
Example 1
Look up a node by ID:
var n = dojo.byId("foo");
Example 2
Check if a node exists, and use it.
var n = dojo.byId("bar");
if(n){ doStuff() ... }
Example 3
Allow string or DomNode references to be passed to a custom function:
var foo = function(nodeOrId){
nodeOrId = dojo.byId(nodeOrId);
// ... more stuff
}
Returns anything|Node|Date|Object
Clones objects (including DOM nodes) and all children.
Warning: do not clone cyclic structures.
| Parameter | Type | Description |
|---|
| o | anything | |
Returns dojo.Color: A dojo.Color object. If obj is passed, it will be the return value.
Builds a dojo.Color from a 3 or 4 element array, mapping each
element in sequence to the rgb(a) values of the color.
| Parameter | Type | Description |
|---|
| a | Array | |
| obj | dojo.Color | Optional. |
Example 1
var myColor = dojo.colorFromArray([237,237,237,0.5]); // grey, 50% alpha
Returns dojo.Color: A dojo.Color object. If obj is passed, it will be the return value.
Converts a hex string with a '#' prefix to a color object.
Supports 12-bit #rgb shorthand. Optionally accepts a
dojo.Color object to update with the parsed value.
| Parameter | Type | Description |
|---|
| color | String | |
| obj | dojo.Color | Optional. |
Example 1
var thing = dojo.colorFromHex("#ededed"); // grey, longhand
Example 2
var thing = dojo.colorFromHex("#000"); // black, shorthand
Returns dojo.Color: A dojo.Color object. If obj is passed, it will be the return value.
this function can handle all 4 CSS3 Color Module formats: rgb,
rgba, hsl, hsla, including rgb(a) with percentage values.
| Parameter | Type | Description |
|---|
| color | String | |
| obj | dojo.Color | Optional. |
A dojo.Color object. If obj is passed, it will be the return value.
Acceptable input values for str may include arrays of any form
accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or
rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10,
10, 50)"
| Parameter | Type | Description |
|---|
| str | String | |
| obj | dojo.Color | Optional. |
Connects listeners to actions, so that after event fires, a
listener is called with the same arguments passed to the original
function.
Since dojo.connect allows the source of events to be either a
"regular" JavaScript function or a DOM event, it provides a uniform
interface for listening to all the types of events that an
application is likely to deal with though a single, unified
interface. DOM programmers may want to think of it as
"addEventListener for everything and anything".
When setting up a connection, the event parameter must be a
string that is the name of the method/event to be listened for. If
obj is null, dojo.global is assumed, meaning that connections
to global methods are supported but also that you may inadvertently
connect to a global by passing an incorrect object name or invalid
reference.
dojo.connect generally is forgiving. If you pass the name of a
function or method that does not yet exist on obj, connect will
not fail, but will instead set up a stub method. Similarly, null
arguments may simply be omitted such that fewer than 4 arguments
may be required to set up a connection See the examples for details.
The return value is a handle that is needed to
remove this connection with dojo.disconnect.
| Parameter | Type | Description |
|---|
| obj | Object|null | The source object for the event function.
Defaults to dojo.global if null.
If obj is a DOM node, the connection is delegated
to the DOM event manager (unless dontFix is true). |
| event | String | name of the event function in obj.
I.e. identifies a property obj[event]. |
| context | Object|null | The object that method will receive as "this".
If context is null and method is a function, then method
inherits the context of event.
If method is a string then context must be the source
object object for method (context[method]). If context is null,
dojo.global is used. |
| method | String|Function | A function reference, or name of a function in context.
The function identified by method fires after event does.
method receives the same arguments as the event.
See context argument comments for information on method's scope. |
| dontFix | Boolean | Optional. If obj is a DOM node, set dontFix to true to prevent delegation
of this connection to the DOM event manager. |
Example 1
When obj.onchange(), do ui.update():
dojo.connect(obj, "onchange", ui, "update");
dojo.connect(obj, "onchange", ui, ui.update); // same
Example 2
Using return value for disconnect:
var link = dojo.connect(obj, "onchange", ui, "update");
...
dojo.disconnect(link);
Example 3
When onglobalevent executes, watcher.handler is invoked:
dojo.connect(null, "onglobalevent", watcher, "handler");
Example 4
When ob.onCustomEvent executes, customEventHandler is invoked:
dojo.connect(ob, "onCustomEvent", null, "customEventHandler");
dojo.connect(ob, "onCustomEvent", "customEventHandler"); // same
Example 5
When ob.onCustomEvent executes, customEventHandler is invoked
with the same scope (this):
dojo.connect(ob, "onCustomEvent", null, customEventHandler);
dojo.connect(ob, "onCustomEvent", customEventHandler); // same
Example 6
When globalEvent executes, globalHandler is invoked
with the same scope (this):
dojo.connect(null, "globalEvent", null, globalHandler);
dojo.connect("globalEvent", globalHandler); // same
Returns Handle
Ensure that every time obj.event() is called, a message is published
on the topic. Returns a handle which can be passed to
dojo.disconnect() to disable subsequent automatic publication on
the topic.
| Parameter | Type | Description |
|---|
| topic | String | The name of the topic to publish. |
| obj | Object|null | The source object for the event function. Defaults to dojo.global
if null. |
| event | String | The name of the event function in obj.
I.e. identifies a property obj[event]. |
Example 1
dojo.connectPublisher("/ajax/start", dojo, "xhrGet");
Returns Object
Returns an object in the expected format of box (regardless if box is passed).
The object might look like:
{ l: 50, t: 200, w: 300: h: 150 }
for a node offset from its parent 50px to the left, 200px from
the top with a content width of 300px and a content-height of
150px. Note that the content box may have a much larger border
or margin box, depending on the box model currently in use and
CSS values set/inherited for node.
While the getter will return top and left values, the
setter only accepts setting the width and height.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to DOM Node to get/set box for |
| box | Object | Optional. If passed, denotes that dojo.contentBox() should
update/set the content box for node. Box is an object in the
above format, but only w (width) and h (height) are supported.
All properties are optional if passed. |
Returns an object that measures margin-box (w)idth/(h)eight
and absolute position x/y of the border-box. Also returned
is computed (l)eft and (t)op values in pixels from the
node's offsetParent as returned from marginBox().
Return value will be in the form:
{ l: 50, t: 200, w: 300: h: 150, x: 100, y: 300 }
Does not act as a setter. If includeScroll is passed, the x and
y params are affected as one would expect in dojo.position().
| Parameter | Type | Description |
|---|
| node | DomNode|String | |
| includeScroll | Boolean | Optional. |
Returns DomNode: DomNode
A DOM Element creation function. A shorthand method for creating a node or
a fragment, and allowing for a convenient optional attribute setting step,
as well as an optional DOM placement reference.
Attributes are set by passing the optional object through dojo.attr.
See dojo.attr for noted caveats and nuances, and API if applicable.
Placement is done via dojo.place, assuming the new node to be the action
node, passing along the optional reference node and position.
| Parameter | Type | Description |
|---|
| tag | String|DomNode | A string of the element to create (eg: "div", "a", "p", "li", "script", "br"),
or an existing DOM node to process. |
| attrs | Object | An object-hash of attributes to set on the newly created node.
Can be null, if you don't want to set any attributes/styles.
See: dojo.attr for a description of available attributes. |
| refNode | String|DomNode | Optional. Optional reference node. Used by dojo.place to place the newly created
node somewhere in the dom relative to refNode. Can be a DomNode reference
or String ID of a node. |
| pos | String | Optional. Optional positional reference. Defaults to "last" by way of dojo.place,
though can be set to "first","after","before","last", "replace" or "only"
to further control the placement of the new node relative to the refNode.
'refNode' is required if a 'pos' is specified. |
Example 1
Create a DIV:
var n = dojo.create("div");
Example 2
Create a DIV with content:
var n = dojo.create("div", { innerHTML:"<p>hi</p>" });
Example 3
Place a new DIV in the BODY, with no attributes set
var n = dojo.create("div", null, dojo.body());
Example 4
Create an UL, and populate it with LI's. Place the list as the first-child of a
node with id="someId":
var ul = dojo.create("ul", null, "someId", "first");
var items = ["one", "two", "three", "four"];
dojo.forEach(items, function(data){
dojo.create("li", { innerHTML: data }, ul);
});
Example 5
Create an anchor, with an href. Place in BODY:
dojo.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
Example 6
Create a `dojo.NodeList()` from a new element (for syntatic sugar):
dojo.query(dojo.create('div'))
.addClass("newDiv")
.onclick(function(e){ console.log('clicked', e.target) })
.place("#someNode"); // redundant, but cleaner.
Returns Function: New constructor function.
Create a constructor using a compact notation for inheritance and
prototype extension.
Mixin ancestors provide a type of multiple inheritance.
Prototypes of mixin ancestors are copied to the new class:
changes to mixin prototypes will not affect classes to which
they have been mixed in.
Ancestors can be compound classes created by this version of
dojo.declare. In complex cases all base classes are going to be
linearized according to C3 MRO algorithm
(see http://www.python.org/download/releases/2.3/mro/ for more
details).
"className" is cached in "declaredClass" property of the new class,
if it was supplied. The immediate super class will be cached in
"superclass" property of the new class.
Methods in "props" will be copied and modified: "nom" property
(the declared name of the method) will be added to all copied
functions to help identify them for the internal machinery. Be
very careful, while reusing methods: if you use the same
function under different names, it can produce errors in some
cases.
It is possible to use constructors created "manually" (without
dojo.declare) as bases. They will be called as usual during the
creation of an instance, their methods will be chained, and even
called by "this.inherited()".
Special property "-chains-" governs how to chain methods. It is
a dictionary, which uses method names as keys, and hint strings
as values. If a hint string is "after", this method will be
called after methods of its base classes. If a hint string is
"before", this method will be called before methods of its base
classes.
If "constructor" is not mentioned in "-chains-" property, it will
be chained using the legacy mode: using "after" chaining,
calling preamble() method before each constructor, if available,
and calling postscript() after all constructors were executed.
If the hint is "after", it is chained as a regular method, but
postscript() will be called after the chain of constructors.
"constructor" cannot be chained "before", but it allows
a special hint string: "manual", which means that constructors
are not going to be chained in any way, and programmer will call
them manually using this.inherited(). In the latter case
postscript() will be called after the construction.
All chaining hints are "inherited" from base classes and
potentially can be overridden. Be very careful when overriding
hints! Make sure that all chained methods can work in a proposed
manner of chaining.
Once a method was chained, it is impossible to unchain it. The
only exception is "constructor". You don't need to define a
method in order to supply a chaining hint.
If a method is chained, it cannot use this.inherited() because
all other methods in the hierarchy will be called automatically.
Usually constructors and initializers of any kind are chained
using "after" and destructors of any kind are chained as
"before". Note that chaining assumes that chained methods do not
return any value: any returned value will be discarded.
| Parameter | Type | Description |
|---|
| className | String: | Optional. The optional name of the constructor (loosely, a "class")
stored in the "declaredClass" property in the created prototype.
It will be used as a global name for a created constructor. |
| superclass | Function|Function[]: | May be null, a Function, or an Array of Functions. This argument
specifies a list of bases (the left-most one is the most deepest
base). |
| props | Object: | An object whose properties are copied to the created prototype.
Add an instance-initialization function by making it a property
named "constructor". |
Example 1
dojo.declare("my.classes.bar", my.classes.foo, {
// properties to be added to the class prototype
someValue: 2,
// initialization function
constructor: function(){
this.myComplicatedObject = new ReallyComplicatedObject();
},
// other functions
someMethod: function(){
doStuff();
}
});
Example 2
var MyBase = dojo.declare(null, {
// constructor, properties, and methods go here
// ...
});
var MyClass1 = dojo.declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyClass2 = dojo.declare(MyBase, {
// constructor, properties, and methods go here
// ...
});
var MyDiamond = dojo.declare([MyClass1, MyClass2], {
// constructor, properties, and methods go here
// ...
});
Example 3
var F = function(){ console.log("raw constructor"); };
F.prototype.method = function(){
console.log("raw method");
};
var A = dojo.declare(F, {
constructor: function(){
console.log("A.constructor");
},
method: function(){
console.log("before calling F.method...");
this.inherited(arguments);
console.log("...back in A");
}
});
new A().method();
// will print:
// raw constructor
// A.constructor
// before calling F.method...
// raw method
// ...back in A
Example 4
var A = dojo.declare(null, {
"-chains-": {
destroy: "before"
}
});
var B = dojo.declare(A, {
constructor: function(){
console.log("B.constructor");
},
destroy: function(){
console.log("B.destroy");
}
});
var C = dojo.declare(B, {
constructor: function(){
console.log("C.constructor");
},
destroy: function(){
console.log("C.destroy");
}
});
new C().destroy();
// prints:
// B.constructor
// C.constructor
// C.destroy
// B.destroy
Example 5
var A = dojo.declare(null, {
"-chains-": {
constructor: "manual"
}
});
var B = dojo.declare(A, {
constructor: function(){
// ...
// call the base constructor with new parameters
this.inherited(arguments, [1, 2, 3]);
// ...
}
});
Example 6
var A = dojo.declare(null, {
"-chains-": {
m1: "before"
},
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = dojo.declare(A, {
"-chains-": {
m2: "after"
},
m1: function(){
console.log("B.m1");
},
m2: function(){
console.log("B.m2");
}
});
var x = new B();
x.m1();
// prints:
// B.m1
// A.m1
x.m2();
// prints:
// A.m2
// B.m2
an Object of anonymous type
This is a small implementaton of the Boodman/Crockford delegation
pattern in JavaScript. An intermediate object constructor mediates
the prototype chain for the returned object, using it to delegate
down to obj for property lookup when object-local lookup fails.
This can be thought of similarly to ES4's "wrap", save that it does
not act on types but rather on pure objects.
| Parameter | Type | Description |
|---|
| obj | The | object to delegate to for properties not found directly on the
return object or in props. |
| props | an | object containing properties to assign to the returned object |
Example 1
var foo = { bar: "baz" };
var thinger = dojo.delegate(foo, { thud: "xyzzy"});
thinger.bar == "baz"; // delegated to foo
foo.thud == undefined; // by definition
thinger.thud == "xyzzy"; // mixed in from props
foo.bar = "thonk";
thinger.bar == "thonk"; // still delegated to foo's bar
Log a debug message to indicate that a behavior has been
deprecated.
| Parameter | Type | Description |
|---|
| behaviour | String | The API or behavior being deprecated. Usually in the form
of "myApp.someFunction()". |
| extra | String | Optional. Text to append to the message. |
| removal | String | Optional. Text to indicate when in the future the behavior will be removed. |
Example 1
dojo.deprecated("myApp.getTemp()", "use myApp.getLocaleTemp() instead", "1.0");
Removes a node from its parent, clobbering it and all of its
children. Function only works with DomNodes, and returns nothing.
| Parameter | Type | Description |
|---|
| node | String|DomNode | A String ID or DomNode reference of the element to be destroyed |
Example 1
Destroy a node byId:
dojo.destroy("someId");
Example 2
Destroy all nodes in a list by reference:
dojo.query(".someNode").forEach(dojo.destroy);
Removes the connection between event and the method referenced by handle.
| Parameter | Type | Description |
|---|
| handle | Handle | the return value of the dojo.connect call that created the connection. |
safely removes all children of the node.
| Parameter | Type | Description |
|---|
| node | DOMNode|String | a reference to a DOM node or an id. |
Example 1
Destroy node's children byId:
dojo.empty("someId");
Example 2
Destroy all nodes' children in a list by reference:
dojo.query(".someNode").forEach(dojo.empty);
Returns Object: The result of the evaluation. Often `undefined`
Placed in a separate function to minimize size of trapped
exceptions. Calling eval() directly from some other scope may
complicate tracebacks on some platforms.
| Parameter | Type | Description |
|---|
| scriptFragment | String | |
Returns Boolean
This function corresponds to the JavaScript 1.6 Array.every() method, with one difference: when
run over sparse arrays, this implemenation passes the "holes" in the sparse array to
the callback function with a value of undefined. JavaScript 1.6's every skips the holes in the sparse array.
For more details, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/every
| Parameter | Type | Description |
|---|
| arr | Array|String | the array to iterate on. If a string, operates on individual characters. |
| callback | Function|String | a function is invoked with three arguments: item, index,
and array and returns true if the condition is met. |
| thisObject | Object | Optional. may be used to scope the call to callback |
Example 1
// returns false
dojo.every([1, 2, 3, 4], function(item){ return item>1; });
Example 2
// returns true
dojo.every([1, 2, 3, 4], function(item){ return item>0; });
Returns Boolean
useful for longer api chains where you have to test each object in
the chain. Useful only for object and method detection.
Not useful for testing generic properties on an object.
In particular, dojo.exists("foo.bar") when foo.bar = ""
will return false. Use ("bar" in foo) to test for those cases.
| Parameter | Type | Description |
|---|
| name | String | Path to an object, in the form "A.B.C". |
| obj | Object | Optional. to use as root of path. Defaults to
'dojo.global'. Null may be passed. |
Example 1
// define an object
var foo = {
bar: { }
};
// search the global scope
dojo.exists("foo.bar"); // true
dojo.exists("foo.bar.baz"); // false
// search from a particular scope
dojo.exists("bar", foo); // true
dojo.exists("bar.baz", foo); // false
| Parameter | Type | Description |
|---|
| exitcode | | |
This can be used to mark a function, file, or module as
experimental. Experimental code is not ready to be used, and the
APIs are subject to change without notice. Experimental code may be
completed deleted without going through the normal deprecation
process.
| Parameter | Type | Description |
|---|
| moduleName | String | The name of a module, or the name of a module file or a specific
function |
| extra | String | Optional. some additional message for the user |
Example 1
dojo.experimental("dojo.data.Result");
Example 2
dojo.experimental("dojo.weather.toKelvin()", "PENDING approval from NOAA");
Returns Object
Adds all properties and methods of props to constructor's
prototype, making them available to all instances created with
constructor.
| Parameter | Type | Description |
|---|
| constructor | Object | |
| props | Object | One or more can be passed. |
Returns dojo.Animation
Returns an animation that will fade node defined in 'args' from
its current opacity to fully opaque.
| Parameter | Type | Description |
|---|
| args | dojo.__FadeArgs | | Parameter | Type | Description |
|---|
| node | DOMNode|String | The node referenced in the animation
| | duration | Integer | Duration of the animation in milliseconds.
|
|
Returns dojo.Animation
Returns an animation that will fade node defined in 'args'
from its current opacity to fully transparent.
| Parameter | Type | Description |
|---|
| args | dojo.__FadeArgs | | Parameter | Type | Description |
|---|
| node | DOMNode|String | The node referenced in the animation
| | duration | Integer | Duration of the animation in milliseconds.
|
|
Returns Object
Returns the value encoded in a form field as
as a string or an array of strings. Disabled form elements
and unchecked radio and checkboxes are skipped. Multi-select
elements are returned as an array of string values.
| Parameter | Type | Description |
|---|
| inputNode | DOMNode||String | |
Returns Array
This function corresponds to the JavaScript 1.6 Array.filter() method, with one difference: when
run over sparse arrays, this implemenation passes the "holes" in the sparse array to
the callback function with a value of undefined. JavaScript 1.6's filter skips the holes in the sparse array.
For more details, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/filter
| Parameter | Type | Description |
|---|
| arr | Array | the array to iterate over. |
| callback | Function|String | a function that is invoked with three arguments (item,
index, array). The return of this function is expected to
be a boolean which determines whether the passed-in item
will be included in the returned array. |
| thisObject | Object | Optional. may be used to scope the call to callback |
Example 1
// returns [2, 3, 4]
dojo.filter([1, 2, 3, 4], function(item){ return item>1; });
normalizes properties on the event object including event
bubbling methods, keystroke normalization, and x/y positions
| Parameter | Type | Description |
|---|
| evt | Event | native event object |
| sender | DOMNode | node to treat as "currentTarget" |
This function corresponds to the JavaScript 1.6 Array.forEach() method, with one difference: when
run over sparse arrays, this implemenation passes the "holes" in the sparse array to
the callback function with a value of undefined. JavaScript 1.6's forEach skips the holes in the sparse array.
For more details, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/forEach
| Parameter | Type | Description |
|---|
| arr | Array|String | the array to iterate over. If a string, operates on individual characters. |
| callback | Function|String | a function is invoked with three arguments: item, index, and array |
| thisObject | Object | Optional. may be used to scope the call to callback |
Example 1
// log out all members of the array:
dojo.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item){
console.log(item);
}
);
Example 2
// log out the members and their indexes
dojo.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item, idx, arr){
console.log(item, "at index:", idx);
}
);
Example 3
// use a scoped object member as the callback
var obj = {
prefix: "logged via obj.callback:",
callback: function(item){
console.log(this.prefix, item);
}
};
// specifying the scope function executes the callback in that scope
dojo.forEach(
[ "thinger", "blah", "howdy", 10 ],
obj.callback,
obj
);
// alternately, we can accomplish the same thing with dojo.hitch()
dojo.forEach(
[ "thinger", "blah", "howdy", 10 ],
dojo.hitch(obj, "callback")
);
Returns String
Create a serialized JSON string from a form node or string
ID identifying the form to serialize
| Parameter | Type | Description |
|---|
| formNode | DOMNode||String | |
| prettyPrint | Boolean | Optional. |
Returns Object
Returns the values encoded in an HTML form as
string properties in an object which it then returns. Disabled form
elements, buttons, and other non-value form elements are skipped.
Multi-select elements are returned as an array of string values.
| Parameter | Type | Description |
|---|
| formNode | DOMNode||String | |
Example 1
This form:
<form id="test_form">
<input type="text" name="blah" value="blah">
<input type="text" name="no_value" value="blah" disabled>
<input type="button" name="no_value2" value="blah">
<select type="select" multiple name="multi" size="5">
<option value="blah">blah</option>
<option value="thud" selected>thud</option>
<option value="thonk" selected>thonk</option>
</select>
</form>
yields this object structure as the result of a call to
formToObject():
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
Returns String
Returns a URL-encoded string representing the form passed as either a
node or string ID identifying the form to serialize
| Parameter | Type | Description |
|---|
| formNode | DOMNode||String | |
Returns Object
Throws for invalid JSON strings, but it does not use a strict JSON parser. It
delegates to eval(). The content passed to this method must therefore come
from a trusted source.
| Parameter | Type | Description |
|---|
| json | String | a string literal of a JSON item, for instance:
'{ "foo": [ "bar", 1, { "baz": "thud" } ] }' |
Returns CSS2Properties
Gets a "computed style" object which can be used to gather
information about the current state of the rendered node.
Note that this may behave differently on different browsers.
Values may have different formats and value encodings across
browsers.
Note also that this method is expensive. Wherever possible,
reuse the returned object.
Use the dojo.style() method for more consistent (pixelized)
return values.
| Parameter | Type | Description |
|---|
| node | DOMNode | A reference to a DOM node. Does NOT support taking an
ID string for speed reasons. |
Example 1
dojo.getComputedStyle(dojo.byId('foo')).borderWidth;
Example 2
Reusing the returned object, avoiding multiple lookups:
var cs = dojo.getComputedStyle(dojo.byId("someNode"));
var w = cs.width, h = cs.height;
Returns Anything
Returns an effective value of a property or an attribute.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute |
Returns Object
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.
| Parameter | Type | Description |
|---|
| name | String | Path to an property, in the form "A.B.C". |
| create | Boolean | Optional. Optional. Defaults to false. If true, Objects will be
created at any point along the 'path' that is undefined. |
| context | Object | Optional. Optional. Object to use as root of path. Defaults to
'dojo.global'. Null may be passed. |
Returns Boolean: true if the requested attribute is specified on the
given element, and false otherwise
Returns true if the requested attribute is specified on the
given element, and false otherwise.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to the element to check |
| name | String | the name of the attribute |
Returns Boolean
Returns whether or not the specified classes are a portion of the
class list currently applied to the node.
| Parameter | Type | Description |
|---|
| node | DomNode|String | String ID or DomNode reference to check the class for. |
| classStr | String | A string class name to look for. |
Example 1
Do something if a node with id="someNode" has class="aSillyClassName" present
if(dojo.hasClass("someNode","aSillyClassName")){ ... }
Returns String: when used as a getter, returns the current hash string.
when used as a setter, returns the new hash string.
Handles getting and setting of location.hash.
- If no arguments are passed, acts as a getter.
- If a string is passed, acts as a setter.
| Parameter | Type | Description |
|---|
| hash | String | Optional. String: the hash is set - #string. |
| replace | Boolean | Optional. Boolean: If true, updates the hash value in the current history
state instead of creating a new history state. |
Returns Function
Returns a function that will only ever execute in the a given scope.
This allows for easy use of object member functions
in callbacks and other places in which the "this" keyword may
otherwise not reference the expected scope.
Any number of default positional arguments may be passed as parameters
beyond "method".
Each of these values will be used to "placehold" (similar to curry)
for the hitched function.
| Parameter | Type | Description |
|---|
| scope | Object | The scope to use when method executes. If method is a string,
scope is also the object containing method. |
| method | Function|String | A function to be hitched to scope, or the name of the method in
scope to be hitched. |
Example 1
dojo.hitch(foo, "bar")();
runs foo.bar() in the scope of foo
Example 2
dojo.hitch(foo, myFunction);
returns a function that runs myFunction in the scope of foo
Example 3
Expansion on the default positional arguments passed along from
hitch. Passed args are mixed first, additional args after.
var foo = { bar: function(a, b, c){ console.log(a, b, c); } };
var fn = dojo.hitch(foo, "bar", 1, 2);
fn(3); // logs "1, 2, 3"
Example 4
var foo = { bar: 2 };
dojo.hitch(foo, function(){ this.bar = 10; })();
execute an anonymous function in scope of fooReturns Number
This method corresponds to the JavaScript 1.6 Array.indexOf method, with one difference: when
run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript
1.6's indexOf skips the holes in the sparse array.
For details on this method, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/indexOf
| Parameter | Type | Description |
|---|
| array | Array | |
| value | Object | |
| fromIndex | Integer | Optional. |
| findLast | Boolean | Optional. |
Returns Boolean
Returns true if it is a built-in function or some other kind of
oddball that *should* report as a function but doesn't
| Parameter | Type | Description |
|---|
| it | anything | |
Returns Boolean
Return true if it is an Array.
Does not work on Arrays created in other windows.
| Parameter | Type | Description |
|---|
| it | anything | |
Returns Boolean: If it walks like a duck and quacks like a duck, return `true`
Doesn't strongly test for "arrayness". Instead, settles for "isn't
a string or number and has a length property". Arguments objects
and DOM collections will return true when passed to
dojo.isArrayLike(), but will return false when passed to
dojo.isArray().
| Parameter | Type | Description |
|---|
| it | anything | |
Returns Boolean
Checks an event for the copy key (meta on Mac, and ctrl anywhere else)
| Parameter | Type | Description |
|---|
| e | Event | Event object to examine |
Returns Boolean
Returns true if node is a descendant of ancestor
| Parameter | Type | Description |
|---|
| node | DomNode|String | string id or node reference to test |
| ancestor | DomNode|String | string id or node reference of potential parent to test against |
Example 1
Test is node id="bar" is a descendant of node id="foo"
if(dojo.isDescendant("bar", "foo")){ ... }
Return true if it is a Function
| Parameter | Type | Description |
|---|
| it | anything | |
Returns true if it is a JavaScript object (or an Array, a Function
or null)
| Parameter | Type | Description |
|---|
| it | anything | |
Returns Boolean
Return true if it is a String
| Parameter | Type | Description |
|---|
| it | anything | |
Returns Number
This method corresponds to the JavaScript 1.6 Array.lastIndexOf method, with one difference: when
run over sparse arrays, the Dojo function invokes the callback for every index whereas JavaScript
1.6's lastIndexOf skips the holes in the sparse array.
For details on this method, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/lastIndexOf
| Parameter | Type | Description |
|---|
| array | Array | |
| value | Object | |
| fromIndex | Integer | Optional. |
This function is mainly a marker for the xdomain loader to know parts of
code that needs be executed outside the function wrappper that is placed around modules.
The init function could be executed more than once, and it should make no assumptions
on what is loaded, or what modules are available. Only the functionality in Dojo Base
is allowed to be used. Avoid using this method. For a valid use case,
see the source for dojox.gfx.
| Parameter | Type | Description |
|---|
| init | Function | a function reference. Executed immediately. |
signal fired when initial environment and package loading is
complete. You should use dojo.addOnLoad() instead of doing a
direct dojo.connect() to this method in order to handle
initialization tasks that require the environment to be
initialized. In a browser host, declarative widgets will
be constructed when this function finishes runing.
Returns Array
This function corresponds to the JavaScript 1.6 Array.map() method, with one difference: when
run over sparse arrays, this implemenation passes the "holes" in the sparse array to
the callback function with a value of undefined. JavaScript 1.6's map skips the holes in the sparse array.
For more details, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/map
| Parameter | Type | Description |
|---|
| arr | Array|String | the array to iterate on. If a string, operates on
individual characters. |
| callback | Function|String | a function is invoked with three arguments, (item, index,
array), and returns a value |
| thisObject | Function | Optional. may be used to scope the call to callback |
Example 1
// returns [2, 3, 4, 5]
dojo.map([1, 2, 3, 4], function(item){ return item+1 });
Returns Object
Getter/setter for the margin-box of node.
Returns an object in the expected format of box (regardless
if box is passed). The object might look like:
{ l: 50, t: 200, w: 300: h: 150 }
for a node offset from its parent 50px to the left, 200px from
the top with a margin width of 300px and a margin-height of
150px.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to DOM Node to get/set box for |
| box | Object | Optional. If passed, denotes that dojo.marginBox() should
update/set the margin box for node. Box is an object in the
above format. All properties are optional if passed. |
Example 1
Retrieve the marginbox of a passed node
var box = dojo.marginBox("someNodeId");
console.dir(box);
Example 2
Set a node's marginbox to the size of another node
var box = dojo.marginBox("someNodeId");
dojo.marginBox("someOtherNode", box);
Returns Object
dojo.mixin can mix multiple source objects into a
destination object which is then returned. Unlike regular
for...in iteration, dojo.mixin is also smart about avoiding
extensions which other toolkits may unwisely add to the root
object prototype
| Parameter | Type | Description |
|---|
| obj | Object | The object to mix properties into. Also the return value. |
| props | Object | One or more can be passed. One or more objects whose values are successively copied into
obj. If more than one of these objects contain the same value,
the one specified last in the function call will "win". |
Example 1
make a shallow copy of an object
var copy = dojo.mixin({}, source);
Example 2
many class constructors often take an object which specifies
values to be configured on the object. In this case, it is
often simplest to call `dojo.mixin` on the `this` object:
dojo.declare("acme.Base", null, {
constructor: function(properties){
// property configuration:
dojo.mixin(this, properties);
console.log(this.quip);
// ...
},
quip: "I wasn't born yesterday, you know - I've seen movies.",
// ...
});
// create an instance of the class and configure it
var b = new acme.Base({quip: "That's what it does!" });
Example 3
copy in properties from multiple objects
var flattened = dojo.mixin(
{
name: "Frylock",
braces: true
},
{
name: "Carl Brutanananadilewski"
}
);
// will print "Carl Brutanananadilewski"
console.log(flattened.name);
// will print "true"
console.log(flattened.braces);
Returns dojo._Url
Returns a dojo._Url object relative to a module.
| Parameter | Type | Description |
|---|
| module | String | |
| url | dojo._Url||String | |
Example 1
var pngPath = dojo.moduleUrl("acme","images/small.png");
console.dir(pngPath); // list the object properties
// create an image and set it's source to pngPath's value:
var img = document.createElement("img");
// NOTE: we assign the string representation of the url object
img.src = pngPath.toString();
// add our image to the document
dojo.body().appendChild(img);
Example 2
you may de-reference as far as you like down the package
hierarchy. This is sometimes handy to avoid lenghty relative
urls or for building portable sub-packages. In this example,
the `acme.widget` and `acme.util` directories may be located
under different roots (see `dojo.registerModulePath`) but the
the modules which reference them can be unaware of their
relative locations on the filesystem:
// somewhere in a configuration block
dojo.registerModulePath("acme.widget", "../../acme/widget");
dojo.registerModulePath("acme.util", "../../util");
// ...
// code in a module using acme resources
var tmpltPath = dojo.moduleUrl("acme.widget","templates/template.html");
var dataPath = dojo.moduleUrl("acme.util","resources/data.json");
Returns String
takes a name/value mapping object and returns a string representing
a URL-encoded version of that object.
| Parameter | Type | Description |
|---|
| map | Object | |
Example 1
this object:
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
yields the following query string:
"blah=blah&multi=thud&multi=thonk"
Returns Function
Calling dojo.partial is the functional equivalent of calling:
dojo.hitch(null, funcName, ...);
| Parameter | Type | Description |
|---|
| method | Function|String | |
Returns DomNode: DomNode
Returned values is the first argument resolved to a DOM node.
.place() is also a method of `dojo.NodeList`, allowing `dojo.query` node lookups.
Attempt to insert node into the DOM, choosing from various positioning options.
Returns the first argument resolved to a DOM node.
| Parameter | Type | Description |
|---|
| node | String|DomNode | id or node reference, or HTML fragment starting with "<" to place relative to refNode |
| refNode | String|DomNode | id or node reference to use as basis for placement |
| position | String|Number | Optional. string noting the position of node relative to refNode or a
number indicating the location in the childNodes collection of refNode.
Accepted string values are:
* before
* after
* replace
* only
* first
* last
"first" and "last" indicate positions as children of refNode, "replace" replaces refNode,
"only" replaces all children. position defaults to "last" if not specified |
Example 1
Place a node by string id as the last child of another node by string id:
dojo.place("someNode", "anotherNode");
Example 2
Place a node by string id before another node by string id
dojo.place("someNode", "anotherNode", "before");
Example 3
Create a Node, and place it in the body element (last child):
dojo.place("<div></div>", dojo.body());
Example 4
Put a new LI as the first child of a list by id:
dojo.place("<li></li>", "someUl", "first");
This method takes a "map" of arrays which one can use to
optionally load dojo modules. The map is indexed by the
possible dojo.name_ values, with two additional values:
"default" and "common". The items in the "default" array will
be loaded if none of the other items have been choosen based on
dojo.name_, set by your host environment. The items in the
"common" array will always be loaded, regardless of which
list is chosen.
| Parameter | Type | Description |
|---|
| modMap | Object | |
Example 1
dojo.platformRequire({
browser: [
"foo.sample", // simple module
"foo.test",
["foo.bar.baz", true] // skip object check in _loadModule (dojo.require)
],
default: [ "foo.sample._base" ],
common: [ "important.module.common" ]
});
If the context stack contains elements, ensure that
subsequent code executes in the *previous* context to the
current context. The current context set ([global,
document]) is returned.
Returns Object
Returns an object of the form:
{ x: 100, y: 300, w: 20, h: 15 }
If includeScroll==true, the x and y values will include any
document offsets that may affect the position relative to the
viewport.
Uses the border-box model (inclusive of border and padding but
not margin). Does not act as a setter.
| Parameter | Type | Description |
|---|
| node | DomNode | |
| includeScroll | Boolean | Optional. |
Returns Object
Each javascript source file is called a resource. When a
resource is loaded by the browser, dojo.provide() registers
that it has been loaded.
Each javascript source file must have at least one
dojo.provide() call at the top of the file, corresponding to
the file name. For example, js/dojo/foo.js must have
dojo.provide("dojo.foo"); before any calls to
dojo.require() are made.
For backwards compatibility reasons, in addition to registering
the resource, dojo.provide() also ensures that the javascript
object for the module exists. For example,
dojo.provide("dojox.data.FlickrStore"), in addition to
registering that FlickrStore.js is a resource for the
dojox.data module, will ensure that the dojox.data
javascript object exists, so that calls like
dojo.data.foo = function(){ ... } don't fail.
In the case of a build where multiple javascript source files
are combined into one bigger file (similar to a .lib or .jar
file), that file may contain multiple dojo.provide() calls, to
note that it includes multiple resources.
| Parameter | Type | Description |
|---|
| resourceName | String | A dot-sperated string identifying a resource. |
Example 1
Safely create a `my` object, and make dojo.require("my.CustomModule") work
dojo.provide("my.CustomModule");
Returns Array
dojo.pushContext treats contexts as a stack. The
auto-detected contexts which are initially provided using
dojo.setContext() require authors to keep state in order to
"return" to a previous context, whereas the
dojo.pushContext and dojo.popContext methods provide a more
natural way to augment blocks of code to ensure that they
execute in a different window or frame without issue. If
called without any arguments, the default context (the
context when Dojo is first loaded) is instead pushed into
the stack. If only a single string is passed, a node in the
intitial context's document is looked up and its
contextWindow and contextDocument properties are used as
the context to push. This means that iframes can be given
an ID and code can be executed in the scope of the iframe's
document in subsequent calls easily.
| Parameter | Type | Description |
|---|
| g | Object|String | Optional. The global context. If a string, the id of the frame to
search for a context and document. |
| d | MDocumentElement | Optional. The document element to execute subsequent code with. |
Returns Object
Create an object representing a de-serialized query section of a
URL. Query keys with multiple values are returned in an array.
| Parameter | Type | Description |
|---|
| str | String | |
Example 1
This string:
"foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&"
results in this object structure:
{
foo: [ "bar", "baz" ],
thinger: " spaces =blah",
zonk: "blarg"
}
Note that spaces and other urlencoded entities are correctly
handled.
An unregistered module is given the default path of ../[module],
relative to Dojo root. For example, module acme is mapped to
../acme. If you want to use a different module name, use
dojo.registerModulePath.
| Parameter | Type | Description |
|---|
| module | String | |
| prefix | String | |
Example 1
If your dojo.js is located at this location in the web root:
/myapp/js/dojo/dojo/dojo.js
and your modules are located at:
/myapp/js/foo/bar.js
/myapp/js/foo/baz.js
/myapp/js/foo/thud/xyzzy.js
Your application can tell Dojo to locate the "foo" namespace by calling:
dojo.registerModulePath("foo", "../../foo");
At which point you can then use dojo.require() to load the
modules (assuming they provide() the same things which are
required). The full code might be:
dojo.registerModulePath("foo", "../../foo");
dojo.require("foo.bar");
dojo.require("foo.baz");
dojo.require("foo.thud.xyzzy");
Removes an attribute from an HTML element.
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to the element to remove the attribute from |
| name | String | the name of the attribute to remove |
Removes the specified classes from node. No dojo.hasClass
check is required.
| Parameter | Type | Description |
|---|
| node | DomNode|String | String ID or DomNode reference to remove the class from. |
| classStr | String|Array | Optional. An optional String class name to remove, or several space-separated
class names, or an array of class names. If omitted, all class names
will be deleted. |
Example 1
Remove a class from some node:
dojo.removeClass("someNode", "firstClass");
Example 2
Remove two classes from some node:
dojo.removeClass("someNode", "firstClass secondClass");
Example 3
Remove two classes from some node (using array):
dojo.removeClass("someNode", ["firstClass", "secondClass"]);
Example 4
Remove all classes from some node:
dojo.removeClass("someNode");
Example 5
Available in `dojo.NodeList()` for multiple removal
dojo.query(".foo").removeClass("foo");
Returns String: String
Returns the substituted string.
Performs parameterized substitutions on a string. Throws an
exception if any parameter is unmatched.
| Parameter | Type | Description |
|---|
| tmpl | String | String to be used as a template. |
| map | Object|Function | If an object, it is used as a dictionary to look up substitutions.
If a function, it is called for every substitution with following
parameters: a whole match, a name, an offset, and the whole template
string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
for more details). |
| pattern | RegEx | Optional. Optional regular expression objects that overrides the default pattern.
Must be global and match one item. The default is: /\{([^\}]+)\}/g,
which matches patterns like that: "{xxx}", where "xxx" is any sequence
of characters, which doesn't include "}". |
Example 1
// uses a dictionary for substitutions:
dojo.replace("Hello, {name.first} {name.last} AKA {nick}!",
{
nick: "Bob",
name: {
first: "Robert",
middle: "X",
last: "Cringely"
}
});
// returns: Hello, Robert Cringely AKA Bob!
Example 2
// uses an array for substitutions:
dojo.replace("Hello, {0} {2}!",
["Robert", "X", "Cringely"]);
// returns: Hello, Robert Cringely!
Example 3
// uses a function for substitutions:
function sum(a){
var t = 0;
dojo.forEach(a, function(x){ t += x; });
return t;
}
dojo.replace(
"{count} payments averaging {avg} USD per payment.",
dojo.hitch(
{ payments: [11, 16, 12] },
function(_, key){
switch(key){
case "count": return this.payments.length;
case "min": return Math.min.apply(Math, this.payments);
case "max": return Math.max.apply(Math, this.payments);
case "sum": return sum(this.payments);
case "avg": return sum(this.payments) / this.payments.length;
}
}
)
);
// prints: 3 payments averaging 13 USD per payment.
Example 4
// uses an alternative PHP-like pattern for substitutions:
dojo.replace("Hello, ${0} ${2}!",
["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
// returns: Hello, Robert Cringely!
the required namespace object
Modules are loaded via dojo.require by using one of two loaders: the normal loader
and the xdomain loader. The xdomain loader is used when dojo was built with a
custom build that specified loader=xdomain and the module lives on a modulePath
that is a whole URL, with protocol and a domain. The versions of Dojo that are on
the Google and AOL CDNs use the xdomain loader.
If the module is loaded via the xdomain loader, it is an asynchronous load, since
the module is added via a dynamically created script tag. This
means that dojo.require() can return before the module has loaded. However, this
should only happen in the case where you do dojo.require calls in the top-level
HTML page, or if you purposely avoid the loader checking for dojo.require
dependencies in your module by using a syntax like dojo["require"] to load the module.
Sometimes it is useful to not have the loader detect the dojo.require calls in the
module so that you can dynamically load the modules as a result of an action on the
page, instead of right at module load time.
Also, for script blocks in an HTML page, the loader does not pre-process them, so
it does not know to download the modules before the dojo.require calls occur.
So, in those two cases, when you want on-the-fly module loading or for script blocks
in the HTML page, special care must be taken if the dojo.required code is loaded
asynchronously. To make sure you can execute code that depends on the dojo.required
modules, be sure to add the code that depends on the modules in a dojo.addOnLoad()
callback. dojo.addOnLoad waits for all outstanding modules to finish loading before
executing.
Example:
<script type="text/javascript">
dojo.require("foo");
dojo.require("bar");
dojo.addOnLoad(function(){
//you can now safely do something with foo and bar
});
</script>
This type of syntax works with both xdomain and normal loaders, so it is good
practice to always use this idiom for on-the-fly code loading and in HTML script
blocks. If at some point you change loaders and where the code is loaded from,
it will all still work.
More on how dojo.require
dojo.require("A.B") first checks to see if symbol A.B is
defined. If it is, it is simply returned (nothing to do).
If it is not defined, it will look for
A/B.js in the script root
directory.
dojo.require throws an excpetion if it cannot find a file
to load, or if the symbol
A.B is not defined after loading.
It returns the object
A.B, but note the caveats above about on-the-fly loading and
HTML script blocks when the xdomain loader is loading a module.
dojo.require() does nothing about importing symbols into
the current namespace. It is presumed that the caller will
take care of that. For example, to import all symbols into a
local block, you might write:
with (dojo.require("A.B")) {
...
}
And to import just the leaf symbol to a local variable:
var B = dojo.require("A.B");
...
| Parameter | Type | Description |
|---|
| moduleName | String | module name to load, using periods for separators,
e.g. "dojo.date.locale". Module paths are de-referenced by dojo's
internal mapping of locations to names and are disambiguated by
longest prefix. See dojo.registerModulePath() for details on
registering new modules. |
| omitModuleCheck | Boolean | Optional. if true, omitModuleCheck skips the step of ensuring that the
loaded file actually defines the symbol it is referenced by.
For example if it called as dojo.require("a.b.c") and the
file located at a/b/c.js does not define an object a.b.c,
and exception will be throws whereas no exception is raised
when called as dojo.require("a.b.c", true) |
If the condition is true then call dojo.require() for the specified
resource
| Parameter | Type | Description |
|---|
| condition | Boolean | |
| resourceName | String | |
Example 1
dojo.requireIf(dojo.isBrowser, "my.special.Module");
Load translated resource bundles provided underneath the "nls"
directory within a package. Translated resources may be located in
different packages throughout the source tree.
Each directory is named for a locale as specified by RFC 3066,
(http://www.ietf.org/rfc/rfc3066.txt), normalized in lowercase.
Note that the two bundles in the example do not define all the
same variants. For a given locale, bundles will be loaded for
that locale and all more general locales above it, including a
fallback at the root directory. For example, a declaration for
the "de-at" locale will first load nls/de-at/bundleone.js,
then nls/de/bundleone.js and finally nls/bundleone.js. The
data will be flattened into a single Object so that lookups
will follow this cascading pattern. An optional build step can
preload the bundles to avoid data redundancy and the multiple
network hits normally required to load these resources.
| Parameter | Type | Description |
|---|
| moduleName | String | name of the package containing the "nls" directory in which the
bundle is found |
| bundleName | String | bundle name, i.e. the filename without the '.js' suffix. Using "nls" as a
a bundle name is not supported, since "nls" is the name of the folder
that holds bundles. Using "nls" as the bundle name will cause problems
with the custom build. |
| locale | String | Optional. the locale to load (optional) By default, the browser's user
locale as defined by dojo.locale |
| availableFlatLocales | String | Optional. A comma-separated list of the available, flattened locales for this
bundle. This argument should only be set by the build process. |
Example 1
A particular widget may define one or more resource bundles,
structured in a program as follows, where moduleName is
mycode.mywidget and bundleNames available include bundleone and
bundletwo:
...
mycode/
mywidget/
nls/
bundleone.js (the fallback translation, English in this example)
bundletwo.js (also a fallback translation)
de/
bundleone.js
bundletwo.js
de-at/
bundleone.js
en/
(empty; use the fallback translation)
en-us/
bundleone.js
en-gb/
bundleone.js
es/
bundleone.js
bundletwo.js
...etc
...
This function is used to mix in properties like dojo._mixin does,
but it skips a constructor property and decorates functions like
dojo.declare does.
It is meant to be used with classes and objects produced with
dojo.declare. Functions mixed in with dojo.safeMixin can use
this.inherited() like normal methods.
This function is used to implement extend() method of a constructor
produced with dojo.declare().
| Parameter | Type | Description |
|---|
| target | Object | Target object to accept new properties. |
| source | Object | Source object for new properties. |
Example 1
var A = dojo.declare(null, {
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = dojo.declare(A, {
m1: function(){
this.inherited(arguments);
console.log("B.m1");
}
});
B.extend({
m2: function(){
this.inherited(arguments);
console.log("B.m2");
}
});
var x = new B();
dojo.safeMixin(x, {
m1: function(){
this.inherited(arguments);
console.log("X.m1");
},
m2: function(){
this.inherited(arguments);
console.log("X.m2");
}
});
x.m2();
// prints:
// A.m1
// B.m1
// X.m1
changes the behavior of many core Dojo functions that deal with
namespace and DOM lookup, changing them to work in a new global
context (e.g., an iframe). The varibles dojo.global and dojo.doc
are modified as a result of calling this function and the result of
dojo.body() likewise differs.
| Parameter | Type | Description |
|---|
| globalObject | Object | |
| globalDocument | DocumentElement | |
Returns Object
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. Returns the passed
value if setting is successful or undefined if not.
| Parameter | Type | Description |
|---|
| name | String | Path to a property, in the form "A.B.C". |
| value | Object | |
| context | Object | Optional. Optional. Object to use as root of path. Defaults to
dojo.global. |
Example 1
set the value of `foo.bar.baz`, regardless of whether
intermediate objects already exist:
dojo.setObject("foo.bar.baz", value);
Example 2
without `dojo.setObject`, we often see code like this:
// ensure that intermediate objects are available
if(!obj["parent"]){ obj.parent = {}; }
if(!obj.parent["child"]){ obj.parent.child= {}; }
// now we can safely set the property
obj.parent.child.prop = "some value";
wheras with `dojo.setObject`, we can shorten that to:
dojo.setObject("parent.child.prop", "some value", obj);
Enable or disable selection on a node
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to node |
| selectable | Boolean | state to put the node in. false indicates unselectable, true
allows selection. |
Example 1
Make the node id="bar" unselectable
dojo.setSelectable("bar");
Example 2
Make the node id="bar" selectable
dojo.setSelectable("bar", true);
Returns Boolean
This function corresponds to the JavaScript 1.6 Array.some() method, with one difference: when
run over sparse arrays, this implemenation passes the "holes" in the sparse array to
the callback function with a value of undefined. JavaScript 1.6's some skips the holes in the sparse array.
For more details, see:
https://developer.mozilla.org/en/CoreJavaScript1.5_Reference/Objects/Array/some
| Parameter | Type | Description |
|---|
| arr | Array|String | the array to iterate over. If a string, operates on individual characters. |
| callback | Function|String | a function is invoked with three arguments: item, index,
and array and returns true if the condition is met. |
| thisObject | Object | Optional. may be used to scope the call to callback |
Example 1
// is true
dojo.some([1, 2, 3, 4], function(item){ return item>1; });
Example 2
// is false
dojo.some([1, 2, 3, 4], function(item){ return item<1; });
prevents propagation and clobbers the default action of the
passed event
| Parameter | Type | Description |
|---|
| evt | Event | The event object. If omitted, window.event is used on IE. |
Getting the style value uses the computed style for the node, so the value
will be a calculated value, not just the immediate node.style value.
Also when getting values, use specific style names,
like "borderBottomWidth" instead of "border" since compound values like
"border" are not necessarily reflected as expected.
If you want to get node dimensions, use dojo.marginBox(),
dojo.contentBox() or dojo.position().
| Parameter | Type | Description |
|---|
| node | DomNode|String | id or reference to node to get/set style for |
| style | String|Object | Optional. the style property to set in DOM-accessor format
("borderWidth", not "border-width") or an object with key/value
pairs suitable for setting each property. |
| value | String | Optional. If passed, sets value on the node for style, handling
cross-browser concerns. When setting a pixel value,
be sure to include "px" in the value. For instance, top: "200px".
Otherwise, in some cases, some browsers will not apply the style. |
Example 1
Passing only an ID or node returns the computed style object of
the node:
dojo.style("thinger");
Example 2
Passing a node and a style property returns the current
normalized, computed value for that property:
dojo.style("thinger", "opacity"); // 1 by default
Example 3
Passing a node, a style property, and a value changes the
current display of the node and returns the new computed value
dojo.style("thinger", "opacity", 0.5); // == 0.5
Example 4
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
dojo.style("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
Example 5
When the CSS style property is hyphenated, the JavaScript property is camelCased.
font-size becomes fontSize, and so on.
dojo.style("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
Example 6
dojo.NodeList implements .style() using the same syntax, omitting the "node" parameter, calling
dojo.style() on every element of the list. See: `dojo.query()` and `dojo.NodeList()`
dojo.query(".someClassName").style("visibility","hidden");
// or
dojo.query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
Returns null|String
Returns a JSON serialization of an object.
Note that this doesn't check for infinite recursion, so don't do that!
| Parameter | Type | Description |
|---|
| it | Object | an object to be serialized. Objects may define their own
serialization via a special "__json__" or "json" function
property. If a specialized serializer has been defined, it will
be used as a fallback. |
| prettyPrint | Boolean | Optional. if true, we indent objects and arrays to make the output prettier.
The variable dojo.toJsonIndentStr is used as the indent string --
to use something other than the default (tab), change that variable
before calling dojo.toJson(). |
| _indentStr | String | Optional. private variable for recursive calls when pretty printing, do not use. |
Example 1
simple serialization of a trivial object
var jsonStr = dojo.toJson({ howdy: "stranger!", isStrange: true });
doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
Example 2
a custom serializer for an objects of a particular class:
dojo.declare("Furby", null, {
furbies: "are strange",
furbyCount: 10,
__json__: function(){
},
});
Adds a class to node if not present, or removes if present.
Pass a boolean condition if you want to explicitly add or remove.
| Parameter | Type | Description |
|---|
| node | DomNode|String | |
| classStr | String|Array | |
| condition | Boolean | Optional. If passed, true means to add the class, false means to remove. |
Example 1
dojo.toggleClass("someNode", "hovered");
Example 2
Forcefully add a class
dojo.toggleClass("someNode", "hovered", true);
Example 3
Available in `dojo.NodeList()` for multiple toggles
dojo.query(".toggleMe").toggleClass("toggleMe");
Returns String: String
Returns the trimmed string
This version of trim() was selected for inclusion into the base due
to its compact size and relatively good performance
(see Steven Levithan's blog
Uses String.prototype.trim instead, if available.
The fastest but longest version of this function is located at
dojo.string.trim()
| Parameter | Type | Description |
|---|
| str | String | String to be trimmed |
signal fired by impending environment destruction. You should use
dojo.addOnUnload() instead of doing a direct dojo.connect() to this
method to perform page/application cleanup methods. See
dojo.addOnUnload for more info.
This provides normalization between normal synchronous values and
asynchronous promises, so you can interact with them in a common way
| Parameter | Type | Description |
|---|
| promiseOrValue | | |
| callback | Function | Optional. |
| errback | Function | Optional. |
| progressHandler | Function | Optional. |
Example 1
function printFirstAndList(items){
dojo.when(findFirst(items), console.log);
dojo.when(findLast(items), console.log);
}
function findFirst(items){
return dojo.when(items, function(items){
return items[0];
});
}
function findLast(items){
return dojo.when(items, function(items){
return items[items.length];
});
}
And now all three of his functions can be used sync or async.
printFirstAndLast([1,2,3,4]) will work just as well as
printFirstAndLast(dojo.xhrGet(...));
signal fired by impending window destruction. You may use
dojo.addOnWIndowUnload() or dojo.connect() to this method to perform
page/application cleanup methods. See dojo.addOnWindowUnload for more info.
Invoke callback with documentObject as dojo.doc. If provided,
callback will be executed in the context of object thisObject
When callback() returns or throws an error, the dojo.doc will
be restored to its previous state.
| Parameter | Type | Description |
|---|
| documentObject | DocumentElement | |
| callback | Function | |
| thisObject | Object | Optional. |
| cbArguments | Array | Optional. |
Invoke callback with globalObject as dojo.global and
globalObject.document as dojo.doc. If provided, globalObject
will be executed in the context of object thisObject
When callback() returns or throws an error, the dojo.global
and dojo.doc will be restored to its previous state.
| Parameter | Type | Description |
|---|
| globalObject | Object | |
| callback | Function | |
| thisObject | Object | Optional. |
| cbArguments | Array | Optional. |
dojo.xdRequireLocalization Internal xd loader function. The xd version of dojo.requireLocalization.
| Parameter | Type | Description |
|---|
| m | | |
| b | | |
| locale | String | Optional. |
| fLocales | | |
| moduleName | String | |
| bundleName | String | |
| availableFlatLocales | String | |
Returns dojo.Deferred
Sends an HTTP request with the given method.
See also dojo.xhrGet(), xhrPost(), xhrPut() and dojo.xhrDelete() for shortcuts
for those HTTP methods. There are also methods for "raw" PUT and POST methods
via dojo.rawXhrPut() and dojo.rawXhrPost() respectively.
| Parameter | Type | Description |
|---|
| method | String | HTTP method to be used, such as GET, POST, PUT, DELETE. Should be uppercase. |
| args | dojo.__XhrArgs | | Parameter | Type | Description |
|---|
| handleAs | String | Acceptable values are: text (default), json, json-comment-optional,
json-comment-filtered, javascript, xml. See dojo.contentHandlers
| | sync | Boolean | false is default. Indicates whether the request should
be a synchronous (blocking) request.
| | headers | Object | Additional HTTP headers to send in the request.
| | failOk | Boolean | false is default. Indicates whether a request should be
allowed to fail (and therefore no console error message in
the event of a failure)
|
|
| hasBody | Boolean | Optional. If the request has an HTTP body, then pass true for hasBody. |
Returns dojo.Deferred
Sends an HTTP DELETE request to the server.
| Parameter | Type | Description |
|---|
| args | dojo.__XhrArgs | | Parameter | Type | Description |
|---|
| handleAs | String | Acceptable values are: text (default), json, json-comment-optional,
json-comment-filtered, javascript, xml. See dojo.contentHandlers
| | sync | Boolean | false is default. Indicates whether the request should
be a synchronous (blocking) request.
| | headers | Object | Additional HTTP headers to send in the request.
| | failOk | Boolean | false is default. Indicates whether a request should be
allowed to fail (and therefore no console error message in
the event of a failure)
|
|
Returns dojo.Deferred
Sends an HTTP GET request to the server.
| Parameter | Type | Description |
|---|
| args | dojo.__XhrArgs | | Parameter | Type | Description |
|---|
| handleAs | String | Acceptable values are: text (default), json, json-comment-optional,
json-comment-filtered, javascript, xml. See dojo.contentHandlers
| | sync | Boolean | false is default. Indicates whether the request should
be a synchronous (blocking) request.
| | headers | Object | Additional HTTP headers to send in the request.
| | failOk | Boolean | false is default. Indicates whether a request should be
allowed to fail (and therefore no console error message in
the event of a failure)
|
|
Returns dojo.Deferred
Sends an HTTP POST request to the server. In addtion to the properties
listed for the dojo.__XhrArgs type, the following property is allowed:
postData:
String. Send raw data in the body of the POST request.
| Parameter | Type | Description |
|---|
| args | dojo.__XhrArgs | | Parameter | Type | Description |
|---|
| handleAs | String | Acceptable values are: text (default), json, json-comment-optional,
json-comment-filtered, javascript, xml. See dojo.contentHandlers
| | sync | Boolean | false is default. Indicates whether the request should
be a synchronous (blocking) request.
| | headers | Object | Additional HTTP headers to send in the request.
| | failOk | Boolean | false is default. Indicates whether a request should be
allowed to fail (and therefore no console error message in
the event of a failure)
|
|
Returns dojo.Deferred
Sends an HTTP PUT request to the server. In addtion to the properties
listed for the dojo.__XhrArgs type, the following property is allowed:
putData:
String. Send raw data in the body of the PUT request.
| Parameter | Type | Description |
|---|
| args | dojo.__XhrArgs | | Parameter | Type | Description |
|---|
| handleAs | String | Acceptable values are: text (default), json, json-comment-optional,
json-comment-filtered, javascript, xml. See dojo.contentHandlers
| | sync | Boolean | false is default. Indicates whether the request should
be a synchronous (blocking) request.
| | headers | Object | Additional HTTP headers to send in the request.
| | failOk | Boolean | false is default. Indicates whether a request should be
allowed to fail (and therefore no console error message in
the event of a failure)
|
|
Events
| Parameter | Type | Description |
|---|
| arr | | |
| obj | | |
| fn | | |