Below are listed all functions that are available in EmbedJS. However, there are some properties on the embed object that aren't functions, so here's a brief description of these:
embed.global holds a reference to the global scope in which EmbedJS was loaded.
In browser context, this will be window.
embed.doc holds a reference to the document in which EmbedJS was loaded. In a non-browser
environment this will be null.
embed.version contains the version string of the loaded EmbedJS version.
All other EmbedJS goodness lies within the functions listed below. For questions, comments and bugs concerning this reference, feel free to send a tweet to @embedjs or report the bug to the EmbedJS bugtracker on github.
| Summary | Adds the specified classes to the end of the class list on the passed node. Will not re-apply duplicate classes. | ||||||||||||
| Examples | Add a class to some node:
embed.addClass("someNode", "anewClass");
Add two classes at once:
embed.addClass("someNode", "firstClass secondClass");
Add two classes at once (using array):
embed.addClass("someNode", ["firstClass", "secondClass"]);
Available via embed.query() for multiple additions
embed.query("ul > li").addClass("firstLevel");
| ||||||||||||
| Feature | Defined in feature "html-class " | ||||||||||||
| Parameters |
|
| Summary | Registers a function to be triggered after the DOM has finished loading and widgets declared in markup have been instantiated. 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.) | ||||||||||||
| Alias | embed.ready() is an alias for embed.addOnLoad() | ||||||||||||
| Examples | embed.addOnLoad(functionPointer);
embed.addOnLoad(object, "functionName");
embed.addOnLoad(object, function(){ /* ... */});
| ||||||||||||
| Feature | Defined in feature "html-ready " | ||||||||||||
| Parameters |
|
| Summary | creates a new <script> tag pointing to the specified URL and adds it to the document. | ||||||||
| Description | Attaches the script element to the DOM. Use this method if you just want to attach a script to the DOM and do not care when or if it loads. | ||||||||
| Differences to Dojo impl | In the Dojo Toolkit, this method is available as dojo.io.script.attach() | ||||||||
| Feature | Defined in feature "transport-script " | ||||||||
| Parameters |
|
| Summary | Gets or sets an attribute on an HTML element. | ||||||||||||||||
| Description | 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 `embed.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 `embed.stopEvent()` on the passed event object instead of returning a boolean value from the handler itself. | ||||||||||||||||
| Returns | 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 | ||||||||||||||||
| Examples | // get the current value of the "foo" attribute on a node
embed.attr(embed.byId("nodeId"), "foo");
// or we can just pass the id:
embed.attr("nodeId", "foo");
// use attr() to set the tab index
embed.attr("nodeId", "tabIndex", 3);
Set multiple values at once, including event handlers:
embed.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
// embed.stopEvent() to ensure that the submission
// doesn't proceed.
embed.stopEvent(e);
// submit the form with Ajax
embed.xhrPost({ form: "formId" });
}
});
Style is s special case: Only set with an object hash of styles
embed.attr("someNode",{
id:"bar",
style:{
width:"200px", height:"100px", color:"#000"
}
});
Again, only set style as an object hash of styles:
var obj = { color:"#fff", backgroundColor:"#000" };
embed.attr("someNode", "style", obj);
// though shorter to use `embed.style()` in this case:
embed.style("someNode", obj);
| ||||||||||||||||
| Feature | Defined in feature "html-attr " | ||||||||||||||||
| Parameters |
|
| Summary | Returns a reference to the body element. |
| Description | Returns the body element of the document that EmbedJS is loaded into. If called in a non-browser environment, it returns undefined. |
| Returns | body element if available, or undefined if not. |
| Feature | Defined in feature "embed " |
| Summary | Returns DOM node with matching `id` attribute or `null` if not found, similar to "$" function in another library. If `id` is a DomNode, this function is a no-op. | ||||||||||||
| Examples | Look up a node by ID:
var n = embed.byId("foo");
Check if a node exists.
if(embed.byId("bar")){ ... }
Allow string or DomNode references to be passed to a custom function:
var foo = function(nodeOrId){
nodeOrId = embed.byId(nodeOrId);
// ... more stuff
}
| ||||||||||||
| Feature | Defined in feature "html-id " | ||||||||||||
| Parameters |
|
| Summary | Clones objects (including DOM nodes) and all children. Warning: do not clone cyclic structures. | ||||||||
| Feature | Defined in feature "lang-clone " | ||||||||
| Parameters |
|
| Summary | `embed.connect` is the core event handling and delegation method in embed. It allows one function to "listen in" on the execution of any other, triggering the second whenever the first is called. Many listeners may be attached to a function, and source functions may be either regular function calls or DOM events. | ||||||||||||||||||||||||
| Description | Connects listeners to actions, so that after event fires, a listener is called with the same arguments passed to the original function. Since `embed.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, `embed.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. `embed.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 `embed.disconnect`. | ||||||||||||||||||||||||
| Alias | embed.on() is an alias for embed.connect() | ||||||||||||||||||||||||
| Examples | When obj.onchange(), do ui.update():
embed.connect(obj, "onchange", ui, "update"); embed.connect(obj, "onchange", ui, ui.update); // sameUsing return value for disconnect: var link = embed.connect(obj, "onchange", ui, "update"); ... embed.disconnect(link);When onglobalevent executes, watcher.handler is invoked: embed.connect(null, "onglobalevent", watcher, "handler");When ob.onCustomEvent executes, customEventHandler is invoked: embed.connect(ob, "onCustomEvent", null, "customEventHandler"); embed.connect(ob, "onCustomEvent", "customEventHandler"); // sameWhen ob.onCustomEvent executes, customEventHandler is invoked with the same scope (this): embed.connect(ob, "onCustomEvent", null, customEventHandler); embed.connect(ob, "onCustomEvent", customEventHandler); // sameWhen globalEvent executes, globalHandler is invoked with the same scope (this): embed.connect(null, "globalEvent", null, globalHandler);
embed.connect("globalEvent", globalHandler); // same
| ||||||||||||||||||||||||
| Feature | Defined in feature "connect-connect " | ||||||||||||||||||||||||
| Parameters |
|
| Summary | Ensure that every time obj.event() is called, a message is published on the topic. Returns a handle which can be passed to embed.disconnect() to disable subsequent automatic publication on the topic. | ||||||||||||||||
| Examples | embed.connectPublisher("/ajax/start", embed, "xhrGet");
| ||||||||||||||||
| Feature | Defined in feature "connect-pubsub " | ||||||||||||||||
| Parameters |
|
| Summary | Create an element, allowing for optional attribute decoration and placement. | ||||||||||||||||||||
| Description | 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 `embed.attr`. See `embed.attr` for noted caveats and nuances, and API if applicable. Placement is done via `embed.place`, assuming the new node to be the action node, passing along the optional reference node and position. | ||||||||||||||||||||
| Returns | DomNode | ||||||||||||||||||||
| Examples | Create a DIV:
var n = embed.create("div");
Create a DIV with content:
var n = embed.create("div", { innerHTML:"<p>hi</p>" });
Place a new DIV in the BODY, with no attributes set
var n = embed.create("div", null, embed.body());
Create an UL, and populate it with LI's. Place the list as the first-child of a
node with id="someId":
var ul = embed.create("ul", null, "someId", "first");
var items = ["one", "two", "three", "four"];
embed.forEach(items, function(data){
embed.create("li", { innerHTML: data }, ul);
});
Create an anchor, with an href. Place in BODY:
embed.create("a", { href:"foo.html", title:"Goto FOO!" }, embed.body());
Use embed.query() for syntatic sugar:
embed.query(embed.create('div'))
.addClass("newDiv")
.onclick(function(e){ console.log('clicked', e.target) })
.place("#someNode"); // redundant, but cleaner.
| ||||||||||||||||||||
| Feature | Defined in feature "html-element " | ||||||||||||||||||||
| Parameters |
|
| Summary | Create a feature-rich constructor from compact notation | ||||||||||||||||
| Description | Create a constructor using a compact notation for inheritance and prototype extension. All superclasses (including mixins) must be Functions (not simple Objects). 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. "className" is cached in "declaredClass" property of the new class. | ||||||||||||||||
| Examples | Declare a class with no ancestors.
embed.declare("my.ClassyThing", null, {
aProperty:"string",
constructor: function(args){
embed.mixin(this, args);
}
});
Declare a class inheriting from my.classed.Foo
embed.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();
}
);
Declare a class inherting from two mixins, handling multiple constructor args
embed.declare("my.ComplexMix", [my.BaseClass, my.MixedClass],{
constructor: function(a, b){
// someone called `new my.ComplexMix("something", "maybesomething");`
}
});
| ||||||||||||||||
| Differences to Dojo impl | There are known issues with mutliple inheritance. In general, declare works fine, but it may not be as precise as the full-blown declare found in current dojo releases. This is a trade-off for a smaller and better performance. | ||||||||||||||||
| Feature | Defined in feature "oo-declare " | ||||||||||||||||
| Parameters |
|
| Summary | boodman/crockford delegation w/ cornford optimization | ||||||||||||
| Feature | Defined in feature "oo-delegate " | ||||||||||||
| Parameters |
|
| Summary | Removes a node from its parent, clobbering it and all of its children. | ||||||||
| Description | Removes a node from its parent, clobbering it and all of its children. Function only works with DomNodes, and returns nothing. | ||||||||
| Examples | Destroy a node byId:
embed.destroy("someId");
Destroy all nodes in a list by reference:
embed.query(".someNode").forEach(embed.destroy);
| ||||||||
| Feature | Defined in feature "html-destroy " | ||||||||
| Parameters |
|
| Summary | Remove a link created by embed.connect. | ||||||||
| Description | Removes the connection between event and the method referenced by handle. | ||||||||
| Feature | Defined in feature "connect-connect " | ||||||||
| Parameters |
|
| Summary | Empties (clears) a DomNode. | ||||||||
| Feature | Defined in feature "html-element " | ||||||||
| Parameters |
|
| Summary | Determines whether or not every item in arr satisfies the condition implemented by callback. | ||||||||||||||||
| Description | This function corresponds to the JavaScript 1.6 Array.every() method. For more details, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every | ||||||||||||||||
| Examples | // returns false
embed.every([1, 2, 3, 4], function(item){ return item>1; });
// returns true
embed.every([1, 2, 3, 4], function(item){ return item>0; });
| ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | Adds all properties and methods of props to constructor's prototype, making them available to all instances created with constructor. | ||||||||||||
| Feature | Defined in feature "oo-extend " | ||||||||||||
| Parameters |
|
| Summary | Returns a new Array with those items from arr that match the condition implemented by callback. | ||||||||||||||||
| Description | This function corresponds to the JavaScript 1.6 Array.filter() method. For more details, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter | ||||||||||||||||
| Examples | // returns [2, 3, 4]
embed.filter([1, 2, 3, 4], function(item){ return item>1; });
| ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | normalizes properties on the event object including event bubbling methods, keystroke normalization, and x/y positions | ||||||||||||
| Feature | Defined in feature "connect-event " | ||||||||||||
| Parameters |
|
| Summary | for every item in arr, callback is invoked. Return values are ignored. If you want to break out of the loop, consider using embed.every() or embed.some(). forEach does not allow breaking out of the loop over the items in arr. | ||||||||||||||||
| Description | This function corresponds to the JavaScript 1.6 Array.forEach() method. For more details, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach | ||||||||||||||||
| Examples | // log out all members of the array:
embed.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item){
console.log(item);
}
);
// log out the members and their indexes
embed.forEach(
[ "thinger", "blah", "howdy", 10 ],
function(item, idx, arr){
console.log(item, "at index:", idx);
}
);
// 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
embed.forEach(
[ "thinger", "blah", "howdy", 10 ],
obj.callback,
obj
);
// alternately, we can accomplish the same thing with embed.hitch()
embed.forEach(
[ "thinger", "blah", "howdy", 10 ],
embed.hitch(obj, "callback")
);
| ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | Parses a JSON string to return a JavaScript object. | ||||||||||||
| Description | Uses native JSON if possible, if not, it delegates to eval(). The content passed to this method must therefore come from a trusted source. | ||||||||||||
| Feature | Defined in feature "json " | ||||||||||||
| Parameters |
|
| Summary | Returns a "computed style" object. | ||||||||
| Description | 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 embed.style() method for more consistent (pixelized) return values. | ||||||||
| Examples | embed.getComputedStyle(embed.byId('foo')).borderWidth;
Reusing the returned object, avoiding multiple lookups:
var cs = embed.getComputedStyle(embed.byId("someNode"));
var w = cs.width, h = cs.height;
| ||||||||
| Returns | CSS property or computed style object. | ||||||||
| Feature | Defined in feature "html-style " | ||||||||
| Parameters |
|
| Summary | Get a property from a dot-separated string, such as "A.B.C" | ||||||||||||||||
| Description | 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. | ||||||||||||||||
| Feature | Defined in feature "lang-object " | ||||||||||||||||
| Parameters |
|
| Summary | Returns 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 | ||||||||||||
| Feature | Defined in feature "html-attr " | ||||||||||||
| Parameters |
|
| Summary | Returns whether or not the specified classes are a portion of the class list currently applied to the node. | ||||||||||||
| Examples | if(embed.hasClass("someNode","aSillyClassName")){ ... }
| ||||||||||||
| Feature | Defined in feature "html-class " | ||||||||||||
| Parameters |
|
| Summary | 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. | ||||||||||||
| Examples | embed.hitch(foo, "bar")();runs foo.bar() in the scope of foo embed.hitch(foo, myFunction);returns a function that runs myFunction in the scope of foo | ||||||||||||
| Feature | Defined in feature "lang-hitch " | ||||||||||||
| Parameters |
|
| Summary | locates the first index of the provided value in the passed array. If the value is not found, -1 is returned. | ||||||||||||||||||||
| Description | This method corresponds to the JavaScript 1.6 Array.indexOf method. For details on this method, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/indexOf | ||||||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||||||
| Parameters |
|
| Summary | Returns true if it is a built-in function or some other kind of oddball that *should* report as a function but doesn't | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Return true if it is an Array | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | similar to embed.isArray() but more permissive | ||||||||
| Description | 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 embed.isArrayLike(), but will return false when passed to embed.isArray(). | ||||||||
| Returns | If it walks like a duck and quacks like a duck, return `true` | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Returns true if it is a Function. | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Returns true if it is a Number. | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Returns true if it is numeric. | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Returns true if it is a JavaScript object (or an Array, a Function or null) | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | Return true if it is a String | ||||||||
| Feature | Defined in feature "lang-is " | ||||||||
| Parameters |
|
| Summary | sends a get request using a dynamically created script tag. | ||||||||
| Differences to Dojo impl | In the Dojo Toolkit, a similar method can be found at dojo.io.script.get() | ||||||||
| Feature | Defined in feature "transport-jsonp " | ||||||||
| Parameters |
|
| Summary | locates the last index of the provided value in the passed array. If the value is not found, -1 is returned. | ||||||||||||||||
| Description | This method corresponds to the JavaScript 1.6 Array.lastIndexOf method. For details on this method, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/lastIndexOf | ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | signal fired when initial environment and package loading is complete. You should use embed.addOnLoad() instead of doing a direct embed.connect() to this method in order to handle initialization tasks that require the environment to be initialized. |
| Feature | Defined in feature "html-ready " |
| Summary | applies callback to each element of arr and returns an Array with the results | ||||||||||||||||
| Description | This function corresponds to the JavaScript 1.6 Array.map() method. For more details, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map | ||||||||||||||||
| Examples | // returns [2, 3, 4, 5]
embed.map([1, 2, 3, 4], function(item){ return item+1 });
| ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | Adds all properties and methods of props to obj and returns the (now modified) obj. | ||||||||||||
| Description | `embed.mixin` can mix multiple source objects into a destionation object which is then returned. Unlike regular `for...in` iteration, `embed.mixin` is also smart about avoiding extensions which other toolkits may unwisely add to the root object prototype | ||||||||||||
| Examples | make a shallow copy of an object
var copy = embed.mixin({}, source);
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 `embed.mixin` on the `this` object:
embed.declare("acme.Base", null, {
constructor: function(properties){
// property configuration:
embed.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!" });
copy in properties from multiple objects
var flattened = embed.mixin(
{
name: "Frylock",
braces: true
},
{
name: "Carl Brutanananadilewski"
}
);
// will print "Carl Brutanananadilewski"
console.log(flattened.name);
// will print "true"
console.log(flattened.braces);
| ||||||||||||
| Feature | Defined in feature "lang-mixin " | ||||||||||||
| Parameters |
|
| Summary | takes a name/value mapping object and returns a string representing a URL-encoded version of that object. | ||||||||
| Examples | this object:
{
blah: "blah",
multi: [
"thud",
"thonk"
]
};
yields the following query string:
"blah=blah&multi=thud&multi=thonk" | ||||||||
| TODO | This originates in embed._base.xhr. Do we want to keep it here or move it over? | ||||||||
| Feature | Defined in feature "uri " | ||||||||
| Parameters |
|
| Summary | `embed.connect` is the core event handling and delegation method in embed. It allows one function to "listen in" on the execution of any other, triggering the second whenever the first is called. Many listeners may be attached to a function, and source functions may be either regular function calls or DOM events. | ||||||||||||||||||||||||
| Description | Connects listeners to actions, so that after event fires, a listener is called with the same arguments passed to the original function. Since `embed.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, `embed.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. `embed.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 `embed.disconnect`. | ||||||||||||||||||||||||
| Alias | embed.on() is an alias for embed.connect() | ||||||||||||||||||||||||
| Examples | When obj.onchange(), do ui.update():
embed.connect(obj, "onchange", ui, "update"); embed.connect(obj, "onchange", ui, ui.update); // sameUsing return value for disconnect: var link = embed.connect(obj, "onchange", ui, "update"); ... embed.disconnect(link);When onglobalevent executes, watcher.handler is invoked: embed.connect(null, "onglobalevent", watcher, "handler");When ob.onCustomEvent executes, customEventHandler is invoked: embed.connect(ob, "onCustomEvent", null, "customEventHandler"); embed.connect(ob, "onCustomEvent", "customEventHandler"); // sameWhen ob.onCustomEvent executes, customEventHandler is invoked with the same scope (this): embed.connect(ob, "onCustomEvent", null, customEventHandler); embed.connect(ob, "onCustomEvent", customEventHandler); // sameWhen globalEvent executes, globalHandler is invoked with the same scope (this): embed.connect(null, "globalEvent", null, globalHandler);
embed.connect("globalEvent", globalHandler); // same
| ||||||||||||||||||||||||
| Feature | Defined in feature "connect-connect " | ||||||||||||||||||||||||
| Parameters |
|
| Summary | Attempt to insert node into the DOM, choosing from various positioning options. Returns the first argument resolved to a DOM node. | ||||||||||||||||
| Returns | Returned values is the first argument resolved to a DOM node. .place() is also a method of `embed.NodeList`, allowing `embed.query` node lookups. | ||||||||||||||||
| Examples | Place a node by string id as the last child of another node by string id:
embed.place("someNode", "anotherNode");
Place a node by string id before another node by string id
embed.place("someNode", "anotherNode", "before");
Create a Node, and place it in the body element (last child):
embed.place("<div></div>", embed.body());
Put a new LI as the first child of a list by id:
embed.place("<li></li>", "someUl", "first");
| ||||||||||||||||
| Feature | Defined in feature "html-element " | ||||||||||||||||
| Parameters |
|
| Summary | Invoke all listener method subscribed to topic. | ||||||||||||
| Examples | embed.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
embed.publish("alerts", [ "read this", "hello world" ]);
| ||||||||||||
| Feature | Defined in feature "connect-pubsub " | ||||||||||||
| Parameters |
|
| Summary | Returns nodes which match the given CSS3 selector, searching the entire document by default but optionally taking a node to scope the search by. Returns an instance of Array. | ||||||||||||
| Description | embed.query() is the swiss army knife of DOM node manipulation in
EmbedJS. Much like Prototype's "$$" (bling-bling) function or JQuery's
"$" function, embed.query provides robust, high-performance
CSS-based node selector support with the option of scoping searches
to a particular sub-tree of a document.
Supported Selectors:
--------------------
embed.query() supports a rich set of CSS3 selectors, including:
* class selectors (e.g., `.foo`)
* node type selectors like `span`
* ` ` descendant selectors
* `>` child element selectors
* `#foo` style ID selectors
* `*` universal selector
* `~`, the immediately preceeded-by sibling selector
* `+`, the preceeded-by sibling selector
* attribute queries:
* `[foo]` attribute presence selector * `[foo='bar']` attribute value exact match * `[foo~='bar']` attribute value list item match * `[foo^='bar']` attribute start match * `[foo$='bar']` attribute end match * `[foo*='bar']` attribute substring match* `:first-child`, `:last-child`, and `:only-child` positional selectors * `:empty` content emtpy selector * `:checked` pseudo selector * `:nth-child(n)`, `:nth-child(2n+1)` style positional calculations * `:nth-child(even)`, `:nth-child(odd)` positional selectors * `:not(...)` negation pseudo selectors Any legal combination of these selectors will work with `embed.query()`, including compound selectors ("," delimited). Very complex and useful searches can be constructed with this palette of selectors and when combined with functions for manipulation presented by queryExtensions, many types of DOM manipulation operations become very straightforward. Unsupported Selectors: ---------------------- While embed.query handles many CSS3 selectors, some fall outside of what's resaonable for a programmatic node querying engine to handle. Currently unsupported selectors include: * namespace-differentiated selectors of any form * all `::` pseduo-element selectors * certain pseduo-selectors which don't get a lot of day-to-day use: * `:root`, `:lang()`, `:target`, `:focus`* all visual and state selectors: * `:root`, `:active`, `:hover`, `:visisted`, `:link`,`:enabled`, `:disabled` * `:*-of-type` pseudo selectors embede.query and XML Documents: ----------------------------- `embed.query` (as of dojo 1.2) supports searching XML documents in a case-sensitive manner. If an HTML document is served with a doctype that forces case-sensitivity (e.g., XHTML 1.1 Strict), embed.query() will detect this and "do the right thing". Case sensitivity is dependent upon the document being searched and not the query used. It is therefore possible to use case-sensitive queries on strict sub-documents (iframes, etc.) or XML documents while still assuming case-insensitivity for a host/root document. | ||||||||||||
| Returns | The matching nodes. DOMCollection is enumerable, so you can use it with embed.forEach. | ||||||||||||
| Examples | search the entire document for elements with the class "foo":
embed.query(".foo");
these elements will match:
<span class="foo"></span> <span class="foo bar"></span> <p class="thud foo"></p>search the entire document for elements with the classes "foo" *and* "bar": embed.query(".foo.bar");
these elements will match:
<span class="foo bar"></span>while these will not: <span class="foo"></span> <p class="thud foo"></p>find `<span>` elements which are descendants of paragraphs and which have a "highlighted" class: embed.query("p span.highlighted");
the innermost span in this fragment matches:
<p class="foo"> <span>... <span class="highlighted foo bar">...</span> </span> </p>set an "odd" class on all odd table rows inside of the table `#tabular_data`, using the `>` (direct child) selector to avoid affecting any nested tables: embed.query("#tabular_data > tbody > tr:nth-child(odd)").addClass("odd");
| ||||||||||||
| Known Issues | On webkit, the following queries will not work as expected:
(Note that these are bugs webkit's querySelector engine.)
embed.query('[foo|="bar"]') // will also return elements with foo="bar"
embed.query('option:checked') // will return an empty list
| ||||||||||||
| Feature | Defined in feature "query " | ||||||||||||
| Parameters |
|
| Summary | Sends an HTTP POST request to the server. In addtion to the properties listed for the embed.__XhrArgs type, the following property is allowed: postData: String. Send raw data in the body of the POST request. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|
| Summary | Sends an HTTP PUT request to the server. In addtion to the properties listed for the embed.__XhrArgs type, the following property is allowed: putData: String. Send raw data in the body of the PUT request. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|
| Summary | Registers a function to be triggered after the DOM has finished loading and widgets declared in markup have been instantiated. 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.) | ||||||||||||
| Alias | embed.ready() is an alias for embed.addOnLoad() | ||||||||||||
| Examples | embed.addOnLoad(functionPointer);
embed.addOnLoad(object, "functionName");
embed.addOnLoad(object, function(){ /* ... */});
| ||||||||||||
| Feature | Defined in feature "html-ready " | ||||||||||||
| Parameters |
|
| Summary | Removes an attribute from an HTML element. | ||||||||||||
| Feature | Defined in feature "html-attr " | ||||||||||||
| Parameters |
|
| Summary | Removes the specified classes from node. No `embed.hasClass` check is required. | ||||||||||||
| Examples | Remove a class from some node:
embed.removeClass("someNode", "firstClass");
Remove two classes from some node:
embed.removeClass("someNode", "firstClass secondClass");
Remove two classes from some node (using array):
embed.removeClass("someNode", ["firstClass", "secondClass"]);
Remove all classes from some node:
embed.removeClass("someNode");
Available embed.query() for multiple removal
embed.query(".foo").removeClass("foo");
| ||||||||||||
| Feature | Defined in feature "html-class " | ||||||||||||
| Parameters |
|
| Summary | Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched. | ||||||||||||||||
| Returns | Returns the substituted string. | ||||||||||||||||
| Examples | // uses a dictionary for substitutions:
embed.replace("Hello, {name.first} {name.last} AKA {nick}!",
{
nick: "Bob",
name: {
first: "Robert",
middle: "X",
last: "Cringely"
}
});
// returns: Hello, Robert Cringely AKA Bob!
// uses an array for substitutions:
embed.replace("Hello, {0} {2}!",
["Robert", "X", "Cringely"]);
// returns: Hello, Robert Cringely!
// uses a function for substitutions:
function sum(a){
var t = 0;
embed.forEach(a, function(x){ t += x; });
return t;
}
embed.replace(
"{count} payments averaging {avg} USD per payment.",
embed.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.
// uses an alternative PHP-like pattern for substitutions:
embed.replace("Hello, ${0} ${2}!",
["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
// returns: Hello, Robert Cringely!
| ||||||||||||||||
| Feature | Defined in feature "lang-string " | ||||||||||||||||
| Parameters |
|
| Summary | Mix in properties skipping a constructor and decorating functions like it is done by embed.declare. | ||||||||||||
| Description | This function is used to mix in properties like embed._mixin does, but it skips a constructor property and decorates functions like embed.declare does. It is meant to be used with classes and objects produced with embed.declare. Functions mixed in with embed.safeMixin can use this.inherited() like normal methods. This function is used to implement extend() method of a constructor produced with embed.declare(). | ||||||||||||
| Examples | var A = embed.declare(null, {
m1: function(){
console.log("A.m1");
},
m2: function(){
console.log("A.m2");
}
});
var B = embed.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();
embed.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
| ||||||||||||
| Feature | Defined in feature "lang-mixin " | ||||||||||||
| Parameters |
|
| Summary | Set a property from a dot-separated string, such as "A.B.C" | ||||||||||||||||
| Description | 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. | ||||||||||||||||
| Examples | set the value of `foo.bar.baz`, regardless of whether
intermediate objects already exist:
embed.setObject("foo.bar.baz", value);
without `embed.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 `embed.setObject`, we can shorten that to:
embed.setObject("parent.child.prop", "some value", obj);
| ||||||||||||||||
| Feature | Defined in feature "lang-object " | ||||||||||||||||
| Parameters |
|
| Summary | Determines whether or not any item in arr satisfies the condition implemented by callback. | ||||||||||||||||
| Description | This function corresponds to the JavaScript 1.6 Array.some() method. For more details, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/some | ||||||||||||||||
| Examples | // is true
embed.some([1, 2, 3, 4], function(item){ return item>1; });
// is false
embed.some([1, 2, 3, 4], function(item){ return item<1; });
| ||||||||||||||||
| Feature | Defined in feature "array " | ||||||||||||||||
| Parameters |
|
| Summary | prevents propagation and clobbers the default action of the passed event | ||||||||
| Feature | Defined in feature "connect-event " | ||||||||
| Parameters |
|
| Summary | Accesses styles on a node. If 2 arguments are passed, acts as a getter. If 3 arguments are passed, acts as a setter. | ||||||||||||||||
| Examples | Passing only an ID or node returns the computed style object of
the node:
embed.style("thinger");
Passing a node and a style property returns the current
node.style value for that property:
embed.style("thinger", "opacity"); // "" by default
Passing a node, a style property, and a value changes the
current display of the node and returns the new style value
embed.style("thinger", "opacity", 0.5); // == 0.5
Passing a node, an object-style style property sets each of the values in turn and returns the computed style object of the node:
embed.style("thinger", {
"opacity": 0.5,
"border": "3px solid black",
"height": "300px"
});
When the CSS style property is hyphenated, the JavaScript property is camelCased.
font-size becomes fontSize, and so on.
embed.style("thinger",{
fontSize:"14pt",
letterSpacing:"1.2em"
});
embed.NodeList implements .style() using the same syntax, omitting the "node" parameter, calling
embed.style() on every element of the list. See: embed.query and embed.NodeList
embed.query(".someClassName").style("visibility","hidden");
// or
embed.query("#baz > div").style({
opacity:0.75,
fontSize:"13pt"
});
| ||||||||||||||||
| Returns | |||||||||||||||||
| Differences to Dojo impl | In opposition to dojo.style(), embed.style() only uses getComputedStyle if only one argument is given (it then acts as a shorthand to embed.getComputedStyle()). If it acts as a getter, it will return the node.style value. | ||||||||||||||||
| Feature | Defined in feature "html-style " | ||||||||||||||||
| Parameters |
|
| Summary | Attach a listener to a named topic. The listener function is invoked whenever the named topic is published (see: embed.publish). Returns a handle which is needed to unsubscribe this listener. | ||||||||||||||||
| Examples | embed.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); });
embed.publish("alerts", [ "read this", "hello world" ]);
| ||||||||||||||||
| Feature | Defined in feature "connect-pubsub " | ||||||||||||||||
| Parameters |
|
| Summary | Converts an array-like object (i.e. arguments, DOMCollection) to an array. Returns a new Array with the elements of obj. | ||||||||||||||||
| Returns | Array | ||||||||||||||||
| Differences to Dojo impl | In the Dojo Toolkit, this method is available as dojo._toArray(). | ||||||||||||||||
| Feature | Defined in feature "lang-toarray " | ||||||||||||||||
| Parameters |
|
| Summary | converts HTML string into DOM nodes. | ||||||||||||
| Examples | Create a table row:
var tr = embed.toDom("<tr><td>First!</td></tr>");
| ||||||||||||
| Differences to Dojo impl | In the Dojo Toolkit, this method is available as dojo._toDom() | ||||||||||||
| Feature | Defined in feature "html-style " | ||||||||||||
| Parameters |
|
| Summary | Adds a class to node if not present, or removes if present. Pass a boolean condition if you want to explicitly add or remove. | ||||||||||||||||
| Examples | embed.toggleClass("someNode", "hovered");
Forcefully add a class
embed.toggleClass("someNode", "hovered", true);
Available embed.query() for multiple toggles
embed.query(".toggleMe").toggleClass("toggleMe");
| ||||||||||||||||
| Feature | Defined in feature "html-class " | ||||||||||||||||
| Parameters |
|
| Summary | Returns a JSON serialization of an object. | ||||||||
| Description | Returns a serialization of an object, uses JSON.stringify() if possible. Note that this doesn't check for infinite recursion, so don't do that! | ||||||||
| Examples | simple serialization of a trivial object
var jsonStr = embed.toJson({ howdy: "stranger!", isStrange: true });
doh.is('{"howdy":"stranger!","isStrange":true}', jsonStr);
a custom serializer for an objects of a particular class:
embed.declare("Furby", null, {
furbies: "are strange",
furbyCount: 10,
__json__: function(){
},
});
| ||||||||
| Feature | Defined in feature "json " | ||||||||
| Parameters |
|
| Summary | Trims whitespace from both sides of the string | ||||||||
| Returns | Returns the trimmed string | ||||||||
| Description | 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](http://blog.stevenlevithan.com/archives/faster-trim-javascript) Uses String.prototype.trim instead, if available. | ||||||||
| FIXME | Move impls into seperate files! | ||||||||
| Feature | Defined in feature "lang-string " | ||||||||
| Parameters |
|
| Summary | Remove a topic listener. | ||||||||
| Examples | var alerter = embed.subscribe("alerts", null, function(caption, message){ alert(caption + "\n" + message); };
...
embed.unsubscribe(alerter);
| ||||||||
| Feature | Defined in feature "connect-pubsub " | ||||||||
| Parameters |
|
| Summary | This provides normalization between normal synchronous values and asynchronous promises, so you can interact with them in a common way | ||||||||||||||||||||
| Examples | 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(...)); | ||||||||||||||||||||
| Feature | Defined in feature "async-when " | ||||||||||||||||||||
| Parameters |
|
| Summary | Sends an HTTP request with the given method. | ||||||||||||||||
| Description | Sends an HTTP request with the given method. See also embed.xhrGet(), xhrPost(), xhrPut() and embed.xhrDelete() for shortcuts for those HTTP methods. There are also methods for "raw" PUT and POST methods via embed.rawXhrPut() and embed.rawXhrPost() respectively. | ||||||||||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||||||||||
| Parameters |
|
| Summary | Sends an HTTP DELETE request to the server. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|
| Summary | Sends an HTTP GET request to the server. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|
| Summary | Sends an HTTP POST request to the server. In addtion to the properties listed for the embed.__XhrArgs type, the following property is allowed: postData: String. Send raw data in the body of the POST request. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|
| Summary | Sends an HTTP PUT request to the server. In addtion to the properties listed for the embed.__XhrArgs type, the following property is allowed: putData: String. Send raw data in the body of the PUT request. | ||||||||
| Feature | Defined in feature "transport-xhr " | ||||||||
| Parameters |
|