Thursday, March 13th, 2008
Getting some $ with Dojo
<>p>
Neil Roberts has posted a great article on Creating Your Own $ with Dojo:
The bling, one of the best global variables in JavaScript. A tool which has come to mean, as a function, a way to locate a node or set of nodes. And, as a namespace, a simple way to access often-used functionality. "This can't be done with Dojo," you insist. But you're wrong, it's really easy. The ideas behind this little symbol are quite simple and I'm going to show you how to create your own customized version of it.
He manages to walk us through a path where he gets $ working in a way that mimics jQuery. He starts with $ = dojo.query; and ends up with:
-
-
$ = dojo.mixin(function(){ return dojo.mixin(dojo.query.apply(this, arguments), $.fn); }, dojo, { fn: {} });
-
He then tackles plugins and using:
-
-
$.fn.click = function(callback){
-
dojo.forEach(this, function(node){
-
dojo.connect(node, "onclick", function(e){
-
callback.call(e.target, e);
-
});
-
});
-
}
-
You end up being able to do:
-
-
$("li.expandable").click(function(e){
-
$(this).toggleClass("expanded");
-
});
-
Very cool indeed!
Related Content:











Great work, looks like the following syntax is also accepted:
$(['li.expandable", "#myID"], startNode)
Excellent article, which explains how to do jQuery-like APIs without a magic hand waving. Instead of “magic” it actually empowers users to implement similar APIs if the need arises. Keep up the good work!