My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
APIDocs  
Overview and Index of plugd Documentation
Featured
Updated Jul 19, 2009 by phigg...@gmail.com

Modules

The bulk of plugd is located in a single file: base.js. Other experimental functionality is available as additional plugins. The other plugins do not necessarily require base.js to operate, though all require Dojo Base.

The following base docs cover the "released" version of plugd. There are additional functions in the code repository version of base.js, but some are omitted in the release by way of "build exclude" tags. For instance, the dojo.conflict() function is bakes into base.js by default, but can be omitted entirely by specifying a build parameter "conflict=off" in the supplied profile.js. See BuildingPlugd for more on that.

Base Overview

Though the code is very easy to read and heavily documented, all the specifics are covered here, with additional commentary and caveats.

dojo.conflict

This function adds a global variable $ to the page, which is more or less an alias to dojo.query. By calling dojo.conflict() anytime after loading base.js, the $ function will be available.

<script type="text/javascript">
dojo.conflict();
// anything that works on the DOM should 
// be _in_ a ready() function, at least initially: 
$(document).ready(function(){
	/* do cool html stuff */
});
</script>

You can turn on conflict by default by setting the djConfig setting conflict to true. Just as Dojo, either via a script tag before including dojo.js:

<script type="text/javascript">
	var djConfig = { conflict: true };
</script>
<script type="text/javascript" src="path/to/dojo.js"></script>

or conveniently on the tag which included dojo.js:

<script type="text/javascript" djConfig="conflict:true"
	src="http://mysite.com/path/to/dojo/dojo.js"
></script>

note: This function is named conflict because it does. Dojo does not typically pollute the global namespace with variables, instead choosing to place everything inside the dojo namespace. Calling dojo.conflict() may have adverse effects if trying to use Dojo concurrently with another JavaScript library which use the $ as part of their API (Including, but not limited to: Prototype, MooTools, and jQuery).

load

dojo.load is a hybrid dojo.require and dojo.addOnLoad. It works as an alias to dojo.require:

dojo.load("dojo.dnd.Source");
dojo.addOnLoad(function(){
	// modules are ready
});

It also work as an alias to dojo.addOnLoad:

dojo.load(function(){
	// DOM ready! lets do things!
});

Any number of arguments can be passed. If the last argument is a function, that function is passed through dojo.addOnLoad:

dojo.load("dojo.NodeList-fx", "dojo.io.script", "plugd.hover", function(){
	// All modules and DOM loaded!
});

This is provided as a convenience shorthand for use in small pages, and provides a very simple API.

unique / generateId

dojo.generateId is an easy way to get a unique DOM id.

var newid = dojo.generateId();
dojo.byId("something").id = newid;

If you wish to prefix the id with something identifiable, pass a base string:

var id = dojo.generateId("plugd_");

generateId is powered by dojo.unique. dojo.unique accepts a function to test for uniqueness. The generateId example could be written as:

var id = dojo.unique(dojo.byId);

The uniqueness-test function must accept a string, and return some truthy value. In the above case, dojo.byId is called with a string until dojo.byId returns 'undefined', indicating there is no node with that particular id in the DOM.

The same can be applied to Dijit:

var thing = new dijit.form.Button({ 
	id: dojo.unique(dijit.byId)
});

Additionally, you can pass an anonymous function, and test ANY form of uniqueness. For example, a light JSONP implementation:

var jsonp_list = {}; // cache

// get a unique placeholder in the object:
var uniquekey = dojo.unique(function(item){
	return !!jsonp_list[item]; 
});

jsonp_list[uniquekey] = function(response){
	// the function which will be called when the script finishes
}

// add a script, courtesy the script.js plugin:
var url = "http://example.com/foo/data?callback=" + uniquekey;
dojo.addScript(url);

qw

A very simple function to turn a string into an array.

var x = dojo.qw("the quick       brown fox");
dojo.forEach(x, console.log, console);
// prints "the", "quick", "brown", "fox" on different lines

show / hide / toggle

These are mostly simple wrapper functions around dojo.style, but provide an optional fadeIn/Out mechanism by passing a parameter to the function. All three functions are provided both in the dojo namespace, and as an extension on dojo.NodeList allowing chaining.

To show a node:

dojo.show("someId");

To fade a node in quickly:

// options are fast, slow, and mild
dojo.show("someId", "fast");

To show a list of nodes:

dojo.query(".someClass").show();

When called with no parameters, these functions are synchronous:

dojo.query(".someClass")
	// hide them immediately
	.hide()
	// position them on-screen
	.style({ position:"absolute", top:"100px", left:"100px" })
	// now async fade the nodes in
	.show("slow");

Toggle() simply toggles the states between show() and hide(), allowing the same parameters.

pub / sub

dojo.sub is simply an alias to dojo.subscribe.

// assign some function to listen to a topic
dojo.sub("/some/topic", function(data){
	console.log(data);
});

dojo.pub is a "magic" version of dojo.publish that allows any number of parameters after the topic to be passed on to the subscribed functions.

dojo.pub("/some/topic", { some:"information" });
dojo.pub("/some/topic", "Hello!", { some:"information" });

The second pub() example will pass the object as arguments1 to the subscribed function. Alternately, you can define the arguments in the function itself:

dojo.sub("/some/topic", function(first, second, third){
	console.log(first, second, third);
});
dojo.pub("/some/topic", "one", "two", "three");

This API is available since 1.3.0, and provided as a convenience over the standard dojo.publish API, which requires an array be explicitly passed, even in the case of a single argument:

dojo.publish("/some/topic", ["one"]);

create / wrap

These are simple DOM creation functions added into both dojo, and dojo.NodeList.

making nodes:

First, dojo.create will create either a single node (such as a <div> tag, or an <a> in the raw:

var n = dojo.create("div");
dojo.place(n, dojo.body(), "first");

Create can also make "complex" markup from a string:

var n = dojo.create("<div class='bar'><a href='foo.html'>bar</a></div>");
dojo.place(n, dojo.body(), "last");

You can also specify a list of attributes to be added to the newly created node by passing an object hash of key/value pairs as the second parameter:

var n = dojo.create("div", { className:"bar", style:"border:2px solid #eee" });
dojo.place(n, dojo.body(), "last");

Create also is attached to NodeList, so you can create() while in a chain:

dojo.query(".bar").create("span").appendTo(".bar").end().removeClass('bar');

NodeList.create() returns a stashed NodeList, so you can properly .end() out of the list of newly created nodes.

query-creator

With plugd, dojo.query can also optionally act as a convenient DOM-creation function as well. Simply pass some "complex" markup to dojo.query(), and a single-item NodeList will be returned with the newly created node in place.

dojo.query("<div class='bar'>baz</div>").removeClass('bar').appendTo("body");

If you would like to create a single node, and convert it to a list:

dojo.query(dojo.create("a")).onclick(function(e){ ... }).appendTo("body");

note: it is important to dojo.place() or query.appendTo() any newly created Dom Nodes, as they will be left in limbo without being put in the DOM.

wrapping nodes

Wrap will wrap a passed node (by reference or by a string id) in the accompanying DOM, just as create() would:

dojo.wrap("someId", "div");

"someId" is a string id of some Dom Node. It can also be a reference:

var n = dojo.byId("someNode").firstChild;
dojo.wrap(n, "span");

note: the "string ID or reference" patter is followed throughout Dojo with the exception of dojo.clone and dojo.connect

Wrap calls dojo.create() under the covers, so the same pattern applies there, too. You can pass either a single node type, or some "complex markup":

var n = dojo.wrap("someId", "<div class='wrapper'></div>");

In the "complex markup" case, the end location of the wrapped node is relevant. The wrapped node will be placed as the first-child of the top-level node.

var n = dojo.wrap("someId", "<div class='w'><span>bar</span></div>");

Assuming the node with id="someId" is a div, the above call will result in markup like:

<div class='w'>
  <div id="someId">old content</div>
  <span>bar</span>
</div>

This is also incredibly useful when working in a NodeList (via dojo.query). Select some set of nodes, and wrap() them in a new type of node:

dojo.query("a.external")
    .wrap("div")
    .onclick(function(e){ e.preventDefault() });

Optionally, wrap() in NodeList will return a new NodeList of the newly created nodes by passing the clone parameter (a Boolean). This is a stashed NodeList, and can be broken out of with .end()

dojo.query("a[href^=http://]")
    .wrap("div", true)
        // "in" the <div> list
        .addClass("surroundingNode")
    .end()
    // back to the <a> list
    .onclick(function(e){ ... });

And finally, wrap() in NodeList can create "complex markup" as well, with the same caveat about the node being wrapped being placed as a first-child in the newly created structure:

dojo.query("span.wrapMe")
    .wrap("<div class='wrapped'><span class='afterWrapMe'>boo</span></div>");

append / appendTo

These functions exist on NodeList explicitly.

.appendTo will append each of the nodes in this list to a matched selector. For example:

// append the node id="bar" to a node id="baz"
dojo.query("#bar").appendTo("#baz");

If the passed selector is unfound, .appendTo fails silently.

.append() will append will append a found node by the passed selector to the NodeList:

// functionally idenditcal to previous example
dojo.query("#baz").append("#bar")

`note:` .append() will continually place() the node as the last node in each of the dojo.query results (NodeList). The result is that the .append()ed node will exist only in the last element in the NodeLost

append() will only use the first element found in the selector list. Optionally, you can clone that node to be appended to each element found in the query() list:

// clone the li in id="foo", and add it to nodes with class="bar"
dojo.query(".bar").append("#foo li", true);

animate

A function to animate NodeList nodes without the need for external modules. Dojo provides extremely robust animation facilities in the several optional modules (dojo.fx, dojo.fx.easing, dojox.fx, dojo.NodeList-fx), which allow for seriously robust FX. Sometimes, however, you desire to quickly animate some properties for "just a few nodes". By using the animation functions already in dojo.js, we can already do this without any extra plugins.

// fade-in all LI's inside id="bar"
dojo.query("#bar li").animate({ opacity: 1 });

.animate() differs from the other optional NodeList-fx animations in two ways:

  • It plays the animation immediately
  • It does not return the Animation instance, thus allowing further chaining

// animate and add a class to each li insize id="bar"
dojo.query("#bar li").animate({ marginLeft:20 }).addClass("bar");

Animations are asynchronous. In the example above, the class "bar" is added to the matched nodes before the .animate() call is complete. In order to wait until the animation is complete, provide an onEnd callback:

var list = dojo.query("#bar li")
	// duration:1000, with onEnd function, and no easing:
	.animate({ marginLeft:20 }, 1000, null, function(){
		list.addClass("bar");
	});

.animate mirrors the dojo.anim API, omitting the first parameter: node. Each node in the list is used to create an individual animation via dojo.anim(thisNode, ...); See the dojo.anim API docs for more details on this function.

note: these animations are created with convenience in mind. If performance is an issue, it is recommended you use the more advanced .animateProperty by including dojo.NodeList-fx:

dojo.require("dojo.NodeList-fx"); // add more FX to $
dojo.addOnLoad(function(){
	// animateProperty doesn't chain:
	dojo.query("div.baz").animateProperty({ 
		properties:{
			opacity:1, marginLeft:20
		},
		duration:1000, onEnd:function(){ ... }
	}).play();
});

This creates a single combined animation, and scales much better on longer lists of nodes. .animate should, however, be adequate in simple cases.

hover / hoverClass

since 1.3.0

This function registers two functions to execute when a node is entered and exited by using the mouse. This method is only attached to dojo.NodeList, meaning it only is accessible by first selecting DOM Node(s) with dojo.query:

// all nodes with class="hoverable"
dojo.query(".hoverable").hover(
	function(e){
	 	// fired on mouse over
	},
	function(e){
		// fired on mouse out
	}
);

The normalized Event object (e) is passed to each function, and contains information about the node. e.target is the node.

.hover() also accepts a single function. If a single function is passed, it is used for both mouse over and exit events. You can differentiate the events by checking the e.type value from the Event object:

dojo.query(".hoverable").hover(function(e){
	var action = (e.type == "mouseover") ? "addClass" : "removeClass";
	dojo[action](e.target, "hoveredClass");
});

If you are using dojo.conflict(), the above could be written as:

$(".hoverable").hover(function(e){
	$(e.target)[(e.type == "mouseover" ? "addClass" : "removeClass")]("hoveredClass");
});

The .hoverClass() method is basically a reduction of the previous example, as it is an exceptionally common task. To add or remove some class automatically on a list of nodes:

dojo.query(".hoverable").hoverClass("over");

This will make any node with class="hoverable" also have the class "over" when the mouse is in that node, and will remove it when the mouse leaves.

end / stash

Some functions on a NodeList return a new instance of a NodeList. end() allows you to "break out" of the new list of nodes, returning back to the last depth returned. stash() is only useful for plugin developers who wish to enable users to end() out of their new list.

For instance, wrap() (when passed true as a second argument) will return a new NodeList with references to the wrapping node. end() will allow you to return out of that, while giving you an opportunity to manipulate the new nodes first:

dojo.query("#bar")
	.wrap("div", true)
		// now we are "in" a new list
		.addClass("bar") // to the <div>
		.place(dojo.body(),"first")
	.end() // break out
	// now we are back to id="bar list"
	.addClass("found")

note: not ALL functions implement stash(), and therefor not all .end() calls will do as you expect. stash() is only used (currently) by plugd methods. Currently, only create() and wrap() implement stash(), though the API is in place should you desire the functionality in your own plugin:

dojo.extend(dojo.NodeList, {
	parentFind: function(){
		// return a new list of the found node's parentNode's
		var list = new dojo.NodeList();
		this.forEach(function(n){
			list.push(n.parentNode);
		})
		return this._stash(list);
	}
});

end() can be called safely at any time. It simply will return the same list it is currently attached to in the event a stashed NodeList is not found.

values

A .val() method is available in dojo.NodeList, which will return the value of the passed node(s), or optionally set the value of a node.

// as a setter:
dojo.query("input[type=text]").val("changed!");

// as a getter (multiple)
var list = dojo.query("input").val(); 
console.log(list); // is an Array of values

// as a getter (single)
var val = dojo.query("input").at(0).val(); 
console.log(val); // a String

If the matched results from a query is only one element, a string of the value is returned. Otherwise, an Array of values is returned. If .val() is used as a setter, the original NodeList is returned to allow further chaining.

// id's are unique, so it will only return one element:
var value = dojo.query("#bySomeId").val();

first, last

These functions register functions to execute for the first and last nodes of the NodeList, and return the NodeList in full. For instance:

dojo.query(".lotsOfNodes")
	.first(function(n){
		// n is just this[0], and fail quietly like forEach will
	})
	.forEach(function(n){
		// n is each node in the list.
	})
	.last(function(n){
		// n is just this[this.length - 1]
	})

first() and last() are available since version 1.3.0

Additional Modules

Here are brief mentions of the remaining (potentially experimental) project code. None of these are included as part of base.js -- but can be used directly as <script> tags or by mixing them in to plugd by following the BuildingPlugd documentation.

ajax.js

Experimental (non-working) Ajax helpers

block.js

Create an overlay and block input to an arbitrary node.

escape.js

Escape and unescape strings as html_entities() would.

experimental.js

Random experiments. Fun to look at, not to use.

exportNS.js

Experimental code to export one namespace into another. Used for MooJo

fixed.js

A cross-browser (optionally animated) position:fixed implementation.

hover.js

A hover-image plugin.

magic.js

In dojo.conflict mode, maps all public dojo.useful functions into the $ function. eg: $.xhrGet();

menu.js

An unobtrusive UL menu plugin. Basic implementation.

node.js

Provides dojo.node(), a function similar to PrototypeJS's $() function. Converts passed node into a Magic Node with special functionality added, similar to a NodeList, though retaining standard Element properties (such a .style. and .id)

parser.js

An extended dojo.parser, which handles the HTML5 data-dojoType attribute.

PeriodicUpdater.js

An implementation of PrototypeJS's PeriodicUpdater class.

plugin.js

A simple function (dojo.plugin()) which will create single-node and nodelist variations from a single function.

script.js

A Basic script loading mechanism. Can be used for lightweight JSONP, cross-domain script loading, or script injection.

social.js

An experimental (prototype) social-submission widget. Animates hover for several social icons.

trans.js

Additional experimental DOM traversal functions.

trigger.js

Provides object and node event triggering. eg: dojo.trigger("someNode", "click") to fire all registered "onclick" handlers for a node. Mixed into NodeList as well as dojo.node (provided the node.js plugin is enabled)

twit.js

A simple Twitter plugin. Supply a username and template.


Sign in to add a comment
Powered by Google Project Hosting