Thursday, June 18th, 2009
Category: Articles
, JavaScript
The intrepid JS hacker Juriy "kangax" Zaytsev has an incredibly detailed post on demystifying named function expressions:
Surprisingly, a topic of named function expressions doesn’t seem to be covered well enough on the web. This is probably why there are so many misconceptions floating around. In this article, I’ll try to summarize both - theoretical and practical aspects of these wonderful Javascript constructs; the good, bad and ugly parts of them.
In a nutshell, named function expressions are useful for one thing only - descriptive function names in debuggers and profilers. Well, there is also a possibility of using function names for recursion, but you will soon see that this is often impractical nowadays. If you don’t care about debugging experience, you have nothing to worry about. Otherwise, read on to see some of the cross-browser glitches you would have to deal with and tips on how work around them.
He then goes into a ton of examples of weirdness in different browsers, and fun code like this:
JAVASCRIPT:
-
-
var f = function g() {
-
return 1;
-
};
-
if (false) {
-
f = function g(){
-
return 2;
-
}
-
};
-
g(); // 2
-
and
JAVASCRIPT:
-
-
var f = function g(){
-
return [
-
arguments.callee == f,
-
arguments.callee == g
-
];
-
};
-
f(); // [true, false]
-
Finally, he shows a couple of techniques for using these correctly in the real world need of shimming:
JAVASCRIPT:
-
-
// 1) enclose declaration with a separate scope
-
var addEvent = (function(){
-
-
var docEl = document.documentElement;
-
-
// 2) declare a variable to assign function to
-
var fn;
-
-
if (docEl.addEventListener) {
-
-
// 3) make sure to give function a descriptive identifier
-
fn = function addEvent(element, eventName, callback) {
-
element.addEventListener(eventName, callback, false);
-
}
-
}
-
else if (docEl.attachEvent) {
-
fn = function addEvent(element, eventName, callback) {
-
element.attachEvent('on' + eventName, callback);
-
}
-
}
-
else {
-
fn = function addEvent(element, eventName, callback) {
-
element['on' + eventName] = callback;
-
}
-
}
-
-
// 4) clean up `addEvent` function created by JScript
-
// make sure to either prepend assignment with `var`,
-
// or declare `addEvent` at the top of the function
-
var addEvent = null;
-
-
// 5) finally return function referenced by `fn`
-
return fn;
-
})();
-
Wednesday, May 20th, 2009
Category: Articles
, MooTools
, jQuery
Normally when you see a title like jQuery vs. MooTools you get ready for the flame bait. You would expect it even more so if you found out that someone from one of the frameworks wrote the post!
Well, Aaron Newton did just that, and I think he did a very good job at trying to keep as unbiased as possible. He can never be perfect since he has a certain viewpoint, and in fact in some ways when you come from that view you can easily under-share your points.
This isn't a rushed piece. Aaron has been thinking about these things for quite some time, and has really pondered it.
It is a fairly long piece, and includes:
MooTools Makes JavaScript Itself More Fun
jQuery Makes the DOM More Fun
Anything You Can Do I Can Do Better
MooTools Lets You Have It Your Way
Chaining as a Design Pattern
Reusing Code with jQuery
Reusing Code with MooTools
Decision Time
Discussion
Monday, March 23rd, 2009
Category: Articles
, JavaScript
, Library
John Hann has written an enjoyable post on debouncing JavaScript methods that comes with a fun back story on a project that John worked on.
John gets to the matter of debouncing:
Debouncing means to coalesce several temporally close signals into one signal. For example, your computer keyboard does this. Every time you hit a key, the contacts actually bounce a few times, causing several signals to be sent to the circuitry. The circuitry determines that the bouncing has ended when no bounces are detected within a certain period (the “detection period”). Since people can’t really type faster than roughly 10 keys per second, any signals happening within 100 msec of each other, for example, are likely part of the same key press. (In practice, you should at least halve this, so about 50 msec for our keyboard example. I have no idea what keyboards really use, by the way. This is just an illustration.)
Whenever I bring up the concept of debouncing, developers try to cast it as just a means of throttling. But that’s not true at all. Throttling is the reduction in rate of a repeating event. Throttling is good for reducing mousemove events to a lesser, manageable rate, for instance.
Debouncing is quite more precise. Debouncing ensures that exactly one signal is sent for an event that may be happening several times — or even several hundreds of times over an extended period. As long as the events are occurring fast enough to happen at least once in every detection period, the signal will not be sent!
Let’s relate this back to our keyboard-oriented user and our huge set of form fields. Throttling here would certainly help. We could reduce the number of XHR requests to a lower rate than the computer’s key repeat rate for sure! However, we’d still be fetching from the back-end more times than necessary, and the occasional re-rendering of the fetched data could temporarily freeze up the browser, deteriorating the user experience.
Debouncing on the other hand could better detect when the user stopped leaning on the keyboard and had arrived at their destination. It’s certainly not perfect. The user still may overshoot their destination, hesitate, and back-track, causing enough delay for the debounce detection period to expire. However, our tests showed that debouncing did a much better job of reducing XHR requests than throttling.
John then shows this in code:
JAVASCRIPT:
-
-
Function.prototype.debounce = function (threshold, execAsap) {
-
var func = this, // reference to original function
-
timeout; // handle to setTimeout async task (detection period)
-
// return the new debounced function which executes the original function only once
-
// until the detection period expires
-
return function debounced () {
-
var obj = this, // reference to original context object
-
args = arguments; // arguments at execution time
-
// this is the detection function. it will be executed if/when the threshold expires
-
function delayed () {
-
// if we're executing at the end of the detection period
-
if (!execAsap)
-
func.apply(obj, args); // execute now
-
// clear timeout handle
-
timeout = null;
-
};
-
// stop any current detection period
-
if (timeout)
-
clearTimeout(timeout);
-
// otherwise, if we're not already waiting and we're executing at the beginning of the waiting period
-
else if (execAsap)
-
func.apply(obj, args); // execute now
-
// reset the waiting period
-
timeout = setTimeout(delayed, threshold || 100);
-
};
-
}
-
There is also a version that doesn't augment Function if that is more to your fancy.
Finally, some uses:
JAVASCRIPT:
-
-
// using debounce in a constructor or initialization function to debounce
-
// focus events for a widget (onFocus is the original handler):
-
this.debouncedOnFocus = this.onFocus.debounce(500, false);
-
this.inputNode.addEventListener('focus', this.debouncedOnFocus, false);
-
-
// to coordinate the debounce of a method for all objects of a certain class, do this:
-
MyClass.prototype.someMethod = function () {
-
/* do something here, but only once */
-
}.debounce(100, true); // execute at start and use a 100 msec detection period
-
-
// wait until the user is done moving the mouse, then execute
-
// (using the stand-alone version)
-
document.onmousemove = debounce(function (e) {
-
/* do something here, but only once after mouse cursor stops */
-
}, 250, false);
-
Category: Articles
, Dojo

Matthew Russell wrote the most in depth article on dojo.gfx that I have seen. It appeared in Linux Journal and has now been re-printed online.
The article runs the gamut. It starts off discussing the place that dojo.gfx lives in the Dojo world:

Then we learn about how gfx abstracts on top of the various underlying graphics subsystems that various browsers expose (Canvas, SVG, VML, Flash, Silverlight, ...). gfx will choose for you automatically, or you can ask to use a particular rendered:
HTML:
-
-
-
djConfig="gfxRenderer:'canvas'"
-
src="http://o.aolcdn.com/dojo/1.2/dojo/dojo.xd.js">
-
</script>
-
Then we delve into the drawing API itself:
JAVASCRIPT:
-
-
dojo.addOnLoad(function() {
-
var node = dojo.byId("surface");
-
var surface = dojox.gfx.createSurface(node, 600, 600);
-
-
rect1 = surface.createRect({
-
/* x and y default to (0,0) */
-
width : 200,
-
height:200
-
})
-
.setFill("red")
-
.setTransform([
-
dojox.gfx.matrix.translate(200,200),
-
dojox.gfx.matrix.rotategAt(45,100,100)
-
])
-
;
-
});
-
From here Matthew covers topics such as manipulating groups, and how you can make areas moveable, and the 2D charting API.
Sunday, February 22nd, 2009
Category: Articles
, Examples
, Showcase
Ryan Doherty has one of those really nice articles that walk you through how to do something that should be easy in CSS but isn't, until you know how: Cross Browser Inline Block.
By the end of it all you will have this:
HTML:
-
-
-
li {
-
width: 200px;
-
min-height: 250px;
-
border: 1px solid #000;
-
display: -moz-inline-stack;
-
display: inline-block;
-
vertical-align: top;
-
margin: 5px;
-
zoom: 1;
-
*display: inline;
-
_height: 250px;
-
}
-
</style>
-
-
-
-
-
<img src="http://farm4.static.flickr.com/3623/3279671785_d1f2e665b6_s.jpg"
-
alt="lobster" width="75" height="75"/>
-
</div>
-
</li>
-
which gets you the following reliably in many browsers:

Along the way you will learn about more IE star hacks, fun with hasLayout, use XUL stacks to help Firefox 2 along, and more. Very nice job Ryan.
Monday, February 16th, 2009
Category: Articles
, JavaScript
This is a guest post by Jared Jacobs of the KaChing, an exciting new way to do your own hedge fund, the Web 2.0 way (a.k.a. don't give it to Madoff!). I was very happy when he said he would be willing to do a post on REST APIs, and what makes a good design.
So you want to write a script that sites all over the web can use to access your REST API, eh? Well, that would be pretty straightforward if it weren’t for two things:
- browser same-origin restrictions on XMLHttpRequests (XHRs) and inter-window/frame access
- the lack of wide browser support for HTML 5-style message passing between windows.
The Same-Origin Policy and its minor browser-specific variations are detailed elsewhere, so I’ll just summarize it with a few key points. I use the term window to mean window object, which can be a top-level page or reside inside a frame or iframe.
- XHRs can only be issued to the same domain as the originating window (not the originating script).
- Two windows can read, write, and call each other’s properties if and only if they are from the same domain (host, port, and scheme).
- There is one notable exception to the previous statement that is consistent across browsers: A window can change (but not necessarily read) the location of its own iframes and of the top window, regardless of their domains.
Recall that native browser primitives for sending or receiving information across domains include frames, iframes, images, scripts, stylesheets, and forms.
With these constraints and possibilities in mind, let’s first consider how best to support GET requests to the REST API.
Transport for GET Requests
XHRs would be the ideal way to retrieve data, since they provide meta information about each response, such as the the HTTP status code, in addition to the content. As noted above, however, other sites cannot use XHRs to directly to access your REST API.
One possible workaround is for each site that uses the JS client to install a server-side proxy on its domain that proxies REST API calls to your servers. That’s a pretty big barrier to the adoption of your JS client, though. We can do better.
Another possibility is having the JS client delegate the XHRs to a helper iframe that it creates specifically for that purpose. The iframe’s page must, of course, reside on the same domain as the REST API. Then there are also the problems of 1) passing the request URI from the parent window to the helper iframe and 2) passing the response status and content from the helper iframe back to the parent window. These problems are manageable, but not worth solving for GET requests, it turns out. We’ll return to them later.
Textual data can also be loaded across domains within scripts and stylesheets, both of which are lighter-weight than iframes and free of same-origin restrictions. To use one of these techniques, you must 1) either embed the data in a comment or encode it as part of either a valid script or stylesheet, and 2) determine when the data has finished loading.
A popular solution that addresses these two issues nicely, sometimes called script transport or JSONP, is formatting the data in JavaScript Object Notation (JSON) and wrapping it in a JS function call. This is the route I chose for kaChing’s JS client. A JSONP request typically includes the callback name as an HTTP request parameter. You’ll want to host a simple proxy on your domain that handles these requests by taking off the callback name parameter, relaying the request to your REST API servers, then formatting the response as the appropriate JS function call. Your JS client should generate a unique callback name for each request to avoid mix-ups in the event that multiple requests overlap in time. Also make sure that your proxy can relay both success and error responses from the REST API to your JS client.
Another nice property of the JSONP approach is that anyone can write a JS client and run a JSONP proxy server for any REST API, then share their JS client with anyone who trusts them.
Two weaknesses of the JSONP approach to be aware of: 1) it adds another failure point (the proxy server), and 2) detecting loading errors is harder with scripts than with XHRs.
Transport for Non-GET Requests
For HTTP methods other than GET (e.g. HEAD, POST, PUT, DELETE), script transport would require disguising the request as a GET, which has different semantics. Then there’s also the fact that a large request might not fit into a single URL. There must be a better alternative.
HTML forms can do POSTs, but that still leaves out the other HTTP methods.
What about the approach we proposed earlier—delegating XHRs to helper iframes? The JS client can construct a hidden iframe each time it needs to make a non-GET request. Iframe construction is quite fast (7-25 ms for most browsers on today’s machines) if the iframe page is small and cached. The request specification (i.e. verb, URL, and possibly parameters and content) can be passed to the helper iframe in its URL fragment.[1] The helper iframe page deserializes the request specification from its URL fragment immediately upon loading and issues the request. Simple enough. Now to relay the server’s response to the parent window. The simplest and most efficient way is HTML 5’s window.postMessage. The latest versions of some browsers support it already, but most people’s browsers don’t yet. (IE 6 & 7 don’t, but IE 8 will.) Unfortunately, the best two alternatives[2] to window.postMessage both require additional cooperation from sites using the JS client.
Approach 1. Sites using the JS client must host a small HTML file that we’ll call caller.html. They should inform your JS client of its URL as an initialization step. When the XHR response arrives, the XHR iframe creates a child iframe pointing to caller.html and including a URL fragment containing the response status, content, and a callback name from the original window. caller.html simply parses its URL fragment and passes the response information to its grandparent window via a direct function call that looks something like this: parent.parent[callbackName](status, responseText).
Approach 2. Sites using the JS client must inform your JS client of the URL of any valid resource on their domain as an initialization step.[3] That’s right, it can be an image, a stylesheet, an HTML page, or anything else—anything they don’t mind you requesting repeatedly. Its content is irrelevant. It just has to exist. We’ll call it cleardot.gif. When the XHR response arrives, the XHR iframe creates a child iframe pointing to cleardot.gif and including a URL fragment containing the response status and content. The JS client will have been polling for the existence of this grandchild iframe and can decode the response from its location’s URL fragment.
For kaChing’s JS client, I chose Approach 1 because it avoids polling and feels less hacky. Asking sites to allow our JS client to reuse an existing resource on their site seems more fragile because the resource’s original purpose may change or disappear someday. I also built in future compatibility with window.postMessage. (For our implementation, see the _send method in kaChing’s client.js. The helper iframe pages are xhr.html and caller.html.)
Regardless of which approach you choose, it’s important for optimal performance that the helper files (both the ones that you are hosting and the ones that your clients are hosting) be long-term cacheable. Also consider having your JS client preload them to warm the browser cache.
The Programming Interface
Now that we’ve decided on transport mechanisms, let’s turn our attention to the JavaScript programming interface. Since our transport mechanisms are all asynchronous, callers who care about the results of their requests will need to provide callbacks.
A first stab might be to have a JS method for each (verb, resource) pair in the REST API:
kaching.getUser(31, function(user) {
// Use user.
});
That approach is certainly clear and simple, and is probably the best pattern for requests with side effects, like POST, PUT, and DELETE.
An improvement for GET requests would be what I call the shopping list pattern, which allows callers to easily request multiple resources together with a single callback:
kaching.get(
kaching.user(31),
kaching.portfolio(31),
kaching.watchlist(31),
function(user, portfolio, watchlist) {
// Use user, portfolio, and watchlist.
});
In addition to the added convenience, this pattern reduces latency by allowing your JS client to request the desired resources in parallel. The two tricky parts in the implementation of this pattern are what I call the joining callback, which collects all of the expected responses before firing, and the use of Function.prototype.apply to invoke the caller’s callback. For a working example of this pattern, see kaching.fetch in kaChing’s client.js.
Other best practices for JavaScript libraries to consider:
- Avoid polluting the global namespace. Define only a single global name (e.g.
kaching).
- Make the loading of your library idempotent, in case it gets included in a page multiple times.
var kaching = kaching || ...;
Authentication
Authentication issues are beyond the scope of this post. If you’re looking for more information on this topic, you might consider starting with the Google Data APIs Authentication Overview.
Your Prize
For making it this far, you’ve earned an invitation to:
The
API Garage Event
1:00pm Sat Feb 21 at kaChing HQ
Come eat, drink, celebrate, meet the kaChing team, and hack on our API.
Oh, and we’re hiring!
| Attempt |
Outcome |
| When the response arrives, set the parent window’s location fragment. |
Doing this adds an annoying new browser history entry. Plus, the new location fragment is visible in the browser’s location bar. |
| Before issuing the request, create a helper iframe with no src attribute in the parent window; then when the response arrives, set its location to that of the parent window plus a fragment. |
In IE 7 this works, but it results in the browser loading the containing page in the helper iframe, a potentially large waste of resources. Permissions errors in Firefox and Safari. |
| Before issuing the request, create a helper iframe with src=”about:blank” in the parent window; then when the response arrives, add a url fragment. |
Permissions errors again while adding the fragment in Firefox and Safari. Permissions error when the parent tried to read the fragment in IE 7. |
| Before issuing the request, create a helper iframe with src=”/favicon.ico” in the parent window; then when the response arrives, add a url fragment. |
This works in IE for sites that have favicons, but it’s not a very robust solution. Plus, if the site’s favicon isn’t very cacheable, your JS client could end up re-downloading it with each API call. |
| Instead of adding the xhr iframe directly to the page, create an intermediate iframe with no src attribute and document.write its content (just the xhr iframe); when the response arrives, the xhr iframe sets the url fragment of its parent, the intermediate iframe. |
I thought this might work because the intermediate iframe inherits the document.domain of its parent, so the parent should be able to poll its location. The problem I encountered was that the intermediate iframe’s window had no location property to set (presumably since that iframe had no src attribute). |
Wednesday, January 14th, 2009
Category: Articles
, JavaScript
Nicholas C. Zakas has taken his long running script post and is now flushing out ways to stop this from happening.
His first post details loops and he offers up a solution to take the synchronicity out of the world:
The secret to unraveling this problem is to evaluate the loop to answer two questions:
- Does the loop have to execute synchronously?
- Does the order in which the loop’s data is processed matter?
If the answer to both of these questions is “no,” then you have some options for splitting up the work done in the loop. The key is to examine the code closely to answer these questions. A typical loop looks like this:
JAVASCRIPT:
-
-
for(var i=0; i <items.length; i++){
-
process(items[i]);
-
}
-
This doesn’t look too bad though may take very long depending on the amount of time necessary to run the process() function. If there’s no code immediately after the loop that depends on the results of the loop executing, then the answer to the first question is “no.” You can clearly see that each iteration through the loop isn’t dependent on the previous iteration because it’s just dealing with one value at a time, so the answer to the second question is “no.” That means the loop can be split in a way that can free up the browser and avoid long-running script warnings.
In Professional JavaScript, Second Edition, I introduce the following function as a way to deal with loops that may take a significant amount of time to execute:
JAVASCRIPT:
-
-
function chunk(array, process, context){
-
var items = array.concat(); //clone the array
-
setTimeout(function(){
-
var item = items.shift();
-
process.call(context, item);
-
-
if (items.length> 0){
-
setTimeout(arguments.callee, 100);
-
}
-
}, 100);
-
}
-
The chunk() function is designed to process an array in small chunks (hence the name), and accepts three arguments: a “to do” list of items, the function to process each item, and an optional context variable for setting the value of this within the process() function. A timer is used to delay the processing of each item (100ms in this case, but feel free to alter for your specific use). Each time through, the first item in the array is removed and passed to the process() function. If there’s still items left to process, another timer is used to repeat the process.
Looking forward to the rest of the series!
Tuesday, January 13th, 2009
Category: Articles

Noupe has another nice roundup, this time they are showing 10 Smart JavaScript Techniques For Manipulating Content.
They share nice content views with demos and how to content. Included in the list is:
- jQuery pageSlide: jQuery pageSlide is a plugin for jQuery that slides the viewable webpage off-screen, revealing and populating a secondary interaction pane. It may be used in a similar manner to Lightbox, where screen real estate and centralization of the user experience are a concern.
- Create a simple ul list with a nice slide-out effect for li elements: We want to obtain this effect: when an user clicks on a link ("Hide"), the related
- element disappear with a nice animated slide out effect. A simple way to implement an animated "disappear" effect using MooTools slideOut()
- Portfolio Layout Idea Using jQuery: Benjamin Sterling created an interesting portfolio layout and added a nice easing method to the main content panel using easeOutQuad and easeInQuad using jQuery easing plugin.
- Creating a Slick Auto-Playing Featured Content Slider: Niall Doherty’s Coda Slider inspired lot of designers and got them started quickly designing around it. Chris Coyier created a Slick Auto-Playing Featured Content Slider using Coda Slider plugin pretty much “out of the box” and added to it.
- Easy Image or Content Slider: Easy Slider enables images or any content to slide horizontally or vertically on click. It is configurable with css alone.
- mooSlide: mooSlide is nice replacement of the common “lightbox” module. It has some interesting options to influence the look and behaviour of the sliding box.
- jQuery.SerialScroll: jQuery.SerialScroll allows you to easily animate any series of elements, by sequentially scrolling them.
- Agile Carousel: Agile Carousel allows you to easily create a custom carousel.
- Animated JavaScript Slideshow: This extremely lightweight JavaScript animated slideshow script includes a number of cool features to to style your content: description support, link support, no naming restrictions, portrait image support, graceful degradation and active thumbnail status.
- Sexy Lightbox 2: Sexy Lightbox 2 is a sexier and lighter clone of the classic Lightbox. Supports displaying images and HTML elements.
- UI.Layout: Was was inspired by the extJS border-layout. The UI.Layout plug-in can create any UI look you want - from simple headers or sidebars, to a complex application with toolbars, menus, help-panels, status bars, sub-forms, etc.
Friday, November 14th, 2008
Category: Articles

Francisco Tolmasky of 280 North has written a very nice piece on adding Undo and Redo to your Web application with Cappuccino.
He creates a very cool sample application, FloorPlan, that shows off much more than undo/redo. He also discusses how Cappuccino gives you built in undo/redo support and how to make it discoverable.
Cappuccino has built-in support that can allow you to plug undo and redo right in by just by adding a few lines of code. In this tutorial, we will be exploring how to add sophisticated undo and redo support to a graphical application in the browser. We won’t be creating the entire application from scratch however, but instead building off of an existing example. We’re doing this for two reasons. For starters, we don’t want to get distracted from our main task by having to wade through unrelated code. Instead we’ll simply review whatever code we need to as we get to it. More importantly, the sample provided is complex enough to serve as a true real-world example, as opposed to the contrived code we’d be forced to put together in the limited scope of space and time of this tutorial. This also has the benefit of displaying the modular nature of undo support in Cappuccino, and how we can add it to an application without knowing every detail of its implementation.
It would be nice to be able to tie into the Undo menu in the browser.
Thursday, August 28th, 2008
Category: Articles
, Editorial
, Standards
I met with a colleague recently who wants to take his project and create a standard on the web that actually gets adopted. We talked for a long time, and when we finished up I pointed him at a paper that had a huge impact on me, called "In Praise of Evolvable Systems" by Clay Shirky.
This paper was written a long time ago in the ancient year of 1996 by the web's timeline, but everything in it still holds on why the web won and some possibilities of how we can move forward from where we are today. Under the tagline for his paper Clay has the summary "Why something as poorly designed as the Web became The Next Big Thing, and what that means for the future."
Clay starts by pointing out how bad the Web is:
If it were April Fool's Day, the Net's only official holiday, and you wanted to design a 'Novelty Protocol' to slip by the Internet Engineering Task Force as a joke, it might look something like the Web:
- The server would use neither a persistent connection nor a store-and-forward model, thus giving it all the worst features of both telnet and e-mail.
- The server's primary method of extensibility would require spawning external processes, thus ensuring both security risks and unpredictable load.
- The server would have no built-in mechanism for gracefully apportioning resources, refusing or delaying heavy traffic, or load-balancing. It would, however, be relatively easy to crash.
- Multiple files traveling together from one server to one client would each incur the entire overhead of a new session call.
- The hypertext model would ignore all serious theoretical work on hypertext to date. In particular, all hypertext links would be one-directional, thus making it impossible to move or delete a piece of data without ensuring that some unknown number of pointers around the world would silently fail.
- The tag set would be absurdly polluted and user-extensible with no central coordination and no consistency in implementation. As a bonus, many elements would perform conflicting functions as logical and visual layout elements.
HTTP and HTML are the Whoopee Cushion and Joy Buzzer of Internet protocols, only comprehensible as elaborate practical jokes. For anyone who has tried to accomplish anything serious on the Web, it's pretty obvious that of the various implementations of a worldwide hypertext protocol, we have the worst one possible.
Except, of course, for all the others.
The web, however, was better than the contenders of that time. He argues that all the other formats, such as Gopher, Interactive TV, and so on were too well designed and had too much internal consistency:
These various [non-web] protocols and services [Gopher, Interactive TV, AOL, etc.] shared two important characteristics: Each was pursuing a design that was internally cohesive, and each operated in a kind of hermetically sealed environment where it interacted not at all with its neighbors. These characteristics are really flip sides of the same coin -- the strong internal cohesion of their design contributed directly to their lack of interoperability. CompuServe and AOL, two of the top online services, couldn't even share resources with one another, much less somehow interoperate with interactive TV or CD-ROMs...In other words, every contender for becoming an "industry standard" for handling information was too strong and too well-designed to succeed outside its own narrow confines. So how did the Web manage to damage and, in some cases, destroy those contenders for the title of The Next Big Thing? Weakness, coupled with an ability to improve exponentially.
Clay then goes on to argue that successful systems must be evolvable and gives three rules:
Evolvable systems -- those that proceed not under the sole direction of one centralized design authority but by being adapted and extended in a thousand small ways in a thousand places at once -- have three main characteristics that are germane to their eventual victories over strong, centrally designed protocols.
- Only solutions that produce partial results when partially implemented can succeed. The network is littered with ideas that would have worked had everybody adopted them. Evolvable systems begin partially working right away and then grow, rather than needing to be perfected and frozen. Think VMS vs. Unix, cc:Mail vs. RFC-822, Token Ring vs. Ethernet.
- What is, is wrong. Because evolvable systems have always been adapted to earlier conditions and are always being further adapted to present conditions, they are always behind the times. No evolving protocol is ever perfectly in sync with the challenges it faces.
- Finally, Orgel's Rule, named for the evolutionary biologist Leslie Orgel -- "Evolution is cleverer than you are". As with the list of the Web's obvious deficiencies above, it is easy to point out what is wrong with any evolvable system at any point in its life. No one seeing Lotus Notes and the NCSA server side-by-side in 1994 could doubt that Lotus had the superior technology; ditto ActiveX vs. Java or Marimba vs. HTTP. However, the ability to understand what is missing at any given moment does not mean that one person or a small central group can design a better system in the long haul.
I know we sometimes get frustrated with the state of the web today, but its useful to know why we are here, and what characteristics any new ideas, features, or standards probably need to have in order to be successful; Clay's paper helps guide me in terms of navigating these issues.
Thursday, July 17th, 2008
Category: Articles

Jeffrey Barke has written up a tutorial detailing how to create a density map with Prototype, the Google Maps API and the HeatMapAPI.
The heat map API looks cool indeed, and that piece of code looks simple:
JAVASCRIPT:
-
-
addHeatMap: function() {
-
var heatMap = new GEOHeatmap();
-
heatMap.Init(this.width, this.height);
-
heatMap.SetData(this.data);
-
var preUrl = heatMap.GetURL();
-
var heatmapOverlay = new HMGoogleOverlay(preUrl);
-
this.map.addOverlay(heatmapOverlay);
-
}
-
Monday, April 14th, 2008
Category: Aptana
, Articles
, JavaScript
, Server
Davey Waterson of the Aptana Jaxer team has posted an article on using jQuery on the server-side with E4X and more that shows an example of server-side Ajax with a popular framework.
The article describes a polling application that features:
- Using jQuery server-side to manipulate a DOM before it's sent to the client
- Doing some database / SQL interactions, server-side in javascript of course
- User sessions in javascript (Jaxer.session.set('status', status);)
- Using E4X on the server-side.
There are fun little features such as nuking portions of the page if the permissions call for it:
JAVASCRIPT:
-
-
$((status == 'voter') ? '.nonvoter' : '.voter').remove();
-
Since the application delivers no JavaScript itself, this would all work even if the user has JavaScript turned off, on a simple mobile phone, etc.
Friday, March 28th, 2008
Category: Articles
, JavaScript
JAVASCRIPT:
-
-
TheRulesAre(function() { with(this) {
-
-
a(Player).mayNot('buyProperty').unless(function(player, property) {
-
return property.owner === null &&
-
player.funds>= property.price;
-
});
-
-
a(Property).mayNot('addHouse').when(it().isMortgaged());
-
}});
-
Composing DSLs in JavaScript is James Coglan's latest perusal into fun with JavaScript and DSLs.
He walks through the building of this DSL in a step by step manner. He uses his JS.Class library, but you could of course substitute your favourite JavaScript library.
Tuesday, March 25th, 2008
Category: Articles
, JavaScript
Because JavaScript is the language of the web browser, and because the web browser has become the dominant application delivery system, and because JavaScript isn't too bad, JavaScript has become the World's Most Popular Programming Language. Its popularity is growing. It is now being embedded in other applications and contexts. JavaScript has become important.
Douglas Crockford got to act all curmudgeonly as he talks on how The World's Most Popular Programming Language Has Fashion and Luck to Thank.
He starts out talking about the black art of languages:
The art in language design is knowing what to leave out. The features of a good language work together harmoniously. A good language helps us to better understand a problem and to find the best expression of its solution.
A good language is composed of a limited set of features. But there is little agreement on which features are best. Programmers can argue endlessly about features and whether a set of features makes one language better than another. Features matter, but we just don't understand yet how they matter.
Language design has more to do with fashion than technology. It may seem strange that fashion is a major factor in the nerdliest of arts, but it is true. A language with radically different syntax, for example, has no hope of finding broad adoption, regardless of the brilliance of its design. This tends to constrain the rate at which languages evolve.
Just like fashion, a programming language is often a product of its time. The deep problem in language design is not technological, it is psychological. A programming language should equip us with structures that help us to reason more effectively.
And then he gets to JavaScript itself, and how it has managed to become the most deployed language in history even with its foibles.
Thursday, March 13th, 2008
Category: Articles
, Dojo
, JavaScript

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:
JAVASCRIPT:
-
-
$ = dojo.mixin(function(){ return dojo.mixin(dojo.query.apply(this, arguments), $.fn); }, dojo, { fn: {} });
-
He then tackles plugins and using:
JAVASCRIPT:
-
-
$.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:
JAVASCRIPT:
-
-
$("li.expandable").click(function(e){
-
$(this).toggleClass("expanded");
-
});
-
Very cool indeed!
Tuesday, February 26th, 2008
Category: Articles
, Canvas
, JavaScript
, Prototype

"agrath" has developed a very nice Canvas example using Prototype that makes use of a common Prototype-isms: Object.extend, Class.create, bind, enumerables, $w, $.
The Polar Clock is a different visualization of time and the example walks through all of the work required to implement it using Prototype 1.6.0.2 and Canvas, including the draw method:
JAVASCRIPT:
-
-
draw:function(){
-
this.clearCanvas();
-
var w = 20;
-
var r = 260;
-
this.date = new Date();
-
var cr = r;
-
$('labels').update()
-
$w("month day weekday space hour min second").reverse().each(function(interval){
-
cr = cr - w - w/2;
-
if(interval != 'space')
-
{
-
var ir = this.intervalToDegrees[interval].bind(this.date)();
-
var i = ((ir / 360) * 255) + 147;
-
var color = this.cc.rgbToCss(this.cc.hslToRgb(i.wrap(0,255),205,127));
-
this.drawSolidArc(color, cr, w, ir.toRadians());
-
$('labels').insert(this.getIntervalLabel[interval].bind(this.date)() + '<br />');
-
}
-
}.bind(this));
-
},
-
The article walks through a lot of Canvas as well as the Prototype side of things. Very thorough.
Next Page »