About the Author: Christian Heilmann is the author of Beginning JavaScript with DOM Scripting and Ajax, and he contributed a chapter on accessible JavaScript to Web Accessibility: Web Standards and Regulatory Compliance. He has worked in web development for almost 9 years for several agencies and .coms, is currently a lead developer at Yahoo! in England. Christian blogs at http://wait-till-i.com.
Frontend engineering rocks right now. The era of boring web sites is over and we’re all into pushing the envelope, erasing boundaries and getting beyond whatever prevents us from building the next killer web application. New companies building quick-turnaround web products spring up like mushrooms and many an old convention of web design is cast aside to make way for quick prototyping and agile development.
The real confusing part of it — at least to me — is that we don’t try out new ways to approach web application development. Instead, there seem to be two separate schools of development approach:
The framework approach relies heavily on the quality of the generated code and the accessibility and usability of the out-of-the-box page widgets and components. The pure web design approach relies on what HTML allows you to do and most of the time doesn’t take scripting-enhanced widgets into consideration.
As there are not many developers that follow both approaches there is a big divide in skill sets. People tend to become experts in one or another and stay within this comfort zone when talking to other developers. This is a real big waste as both factions could learn a lot from each other. All we need to overcome are the competing notions that (a) web standards and accessibility are show-stoppers for rapid framework-driven development and that (b) frameworks are a source of bad and invalid code. Both approaches are flexible: Frameworks can be extended to produce cleaner code and web standards can be seen as an agreed way of working with one another rather than as immutable laws that are never to be broken.
The sad truth now is that both approaches often lead to hard-to-maintain products that don’t scale gracefully and are a pain to make accessible, localise to different languages or customise to different needs and channels. This is caused by false assumptions made by practitioners of both approaches:
The crux of the matter is that we don’t really yet understand how to build a real web application. We take tried and true methodologies that cover other development scenarios and try to shoe-horn them into something that helps us to achieve what we want on-time and within budget (and when was the last time that happened?).
The other problem is that we approach web application design with browser limitations in mind and plan only for what browsers can do rather than what the application should offer the user.
When it boils down to it, the main differentiator of a web application and a web site is that an app has much more interaction and is process-focused rather than content-driven. Users come in to achieve a goal: They provide data to the application, they use the application to enhance that data, and then they expect data to come out. They interact with components of the application and expect them to do something that brings them closer to their goal. It is of utmost importance that we plan for how users interact with the product and react accordingly.
When trying to accomplish this in the browser, there is one core technique at our disposal: Event handling.
We must try to understand what an event is when it comes to user interaction through the duration of a user session.
Events as defined by the W3C are very complex and can be tough to understand. However, the most common way of thinking about events in JavaScript is:
Most framework-generated code or even handcoded methods use this kind of event handling. We take the window, or a certain element and add handlers defining the event that should trigger a function. This leads to a rigid relationship between the markup and the functionality. As the interface of a web application might change (more links in a component, other buttons, more complex forms) this need to add more cruft begins to cripple our applications. It also means that maintenance must happen in two places — a change to our HTML means that our JavaScript needs to change, too.
The DOM Event Model however goes a bit further. It has a more granular definition of the workflow:
cancelEvent() method and you can retrieve the object the event occurred on, the event target, with a helper method called getTarget().Understanding and implementing this event model can free your application from the constraints of defined elements. For example, instead of applying an event listener for each link in a menu, you can assign a single listener to the menu item itself and retrieve the event target. That way you don’t need to change your script when the menu gets larger or when links get removed from it.
This is a very powerful and flexible approach often referred to as event delegation. Event delegation allows you to react to changes in the document while applying fewer event listeners. You can assign different handlers to different parts of your document (the menu, the main content, a sidebar, a language change menu) and define methods for each event (was it clicked? was a key pressed on it?). These methods then retrieve the element that was affected and react accordingly; for example, you can react differently for links versus buttons.
When using this idea (waiting for an event, investigating where it happens and acting accordingly) in web applications we mostly confine ourselves to what the browser reports us — the DOM events. This is not really necessary, and it’s a big limitation. Much that happens in an application — like a user switching between tabs in a TabView Control — could be thought of as an event and dealt with in the same manner.
You can apply the same DOM-event style logic to anything that happens within your application itself. You can plan your application that way from the outset:
The only thing that’s missing is turning this event plan (once it is finished for the first phase) into real code, and this is where the browser or JavaScript does not give us the built-in interfaces that we’d like to have for the purpose.
Whenever the browser or JavaScript itself lets us down we turn to JavaScript libraries to solve the problem. In this case we’ll use the Yahoo! User Interface Library (YUI) with its Custom Event Object. This object allows you to define any event you like, subscribe listener methods to it, and fire the event whenever you want. It’s like simulating a click on a button. Internally, the YUI uses Custom Events a lot to trigger different reactions. For example the Animation utility allows not only for the animation of elements but makes it easy to create successive animations by providing onStart, onComplete and onTween Custom Events.
Using these events you can put together a web app that is easy to change, extend and maintain.
Let’s take a look at an example how all of this could work. As our application example we have an HTML document with two components: one to change the language, and another to change the layout. The application links DOM events (such as click events when the user clicks on links) to meaningful "interesting moments" in the application, moments that we encapsulate in Custom Events; for example, the user choosing to change the layout of the page is encapsulated in a Custom Event, and when that event is triggered we activate the scripts which perform layout modification.
All links here point to PHP scripts that would perform similar transformations on the server side to ensure that we are not dependent on JavaScript (for this example, however, we’ll look only at the client-side code).
<ul>
<li>Change Language:
<ul id="languages">
<li><a href="test.php?lang=en">English</a></li>
<li><a href="test.php?lang=de">Deutsch</a></li>
<li><a href="test.php?lang=nl">Neederlands</a></li>
</ul>
</li>
</ul>
<ul>
<li>Change Layout:
<ul id="layout">
<li><a href="test.php?layout=onecolumn">One Column</a></li>
<li><a href="test.php?layout=threecolumns">Three Columns</a></li>
</ul>
</li>
</ul>
Now for the important bit: we define an event plan with Custom Events and subscribe the necessary tool methods to each custom event:
// Changing the language
languageChange = new YAHOO.util.CustomEvent('language change');
languageChange.subscribe(retrieveData);
languageChange.subscribe(renderLayout);
languageChange.subscribe(ads);
languageChange.subscribe(pageWidgets);
// Changing the layout
layoutChange = new YAHOO.util.CustomEvent('layout change');
layoutChange.subscribe(renderLayout);
layoutChange.subscribe(ads);
layoutChange.subscribe(pageWidgets);
Adding or removing tool methods here makes it very easy to extend the application by adding or removing functionality without having to change any of the methods themselves. We can also add and remove whole modules of component logic simply by commenting them out.
The tool methods used are stubs in this example, and all they do is report that they were activated:
function retrieveData(type,args){
log('retrieving Data for ' + args[0]);
};
function renderLayout(type,args){
if(type==='layout change'){
log('changing layout for ' + args[0]);
} else {
log('changing language layout for ' + args[0]);
}
};
function ads(type,args){
log('changing ads for ' + args[0]);
};
function pageWidgets(type,args){
log('changing page widgets for ' + args[0]);
};
function log(msg){
document.getElementById('output').innerHTML+='<p>'+msg+'</p>';
}
In the main JavaScript, we’ll apply the normal browser handlers to the components via Event Delegation, get the settings that should be applied from the links and fire the Custom Events. The important parts are in bold:
function initLanguages(){
YAHOO.util.Event.addListener(this, "click", changeLanguage);
};
function initLayout(){
YAHOO.util.Event.addListener(this, "click", changeLayout);
};
function changeLanguage(e){
var t=YAHOO.util.Event.getTarget(e);
if(t.nodeName.toLowerCase()==='a'){
document.getElementById('output').innerHTML = '';
var lang = t.href.replace(/.*?lang=/,'');
languageChange.fire(lang);
}
YAHOO.util.Event.preventDefault(e);
};
function changeLayout(e){
var t=YAHOO.util.Event.getTarget(e);
if(t.nodeName.toLowerCase()==='a'){
document.getElementById('output').innerHTML = '';
var lang = t.href.replace(/.*?layout=/,'');
layoutChange.fire(lang);
}
YAHOO.util.Event.preventDefault(e);
};
YAHOO.util.Event.onAvailable('languages', initLanguages);
YAHOO.util.Event.onAvailable('layout', initLayout);
You can download the demo or try it out for yourself.
You could argue that the same functionality could be achieved without Custom Event handling (by having methods that encapsulate all subsidiary methods to be called for each event). The difference here is that we took the procedural nature of JavaScript out of the equation and we really link the interesting moments of the interaction to the relevant components of our application’s functionality in a single, centralized repository.
This also means that we can make a logging component subscribe to each of the events and store the current state of the whole application in a data repository, allowing for easily implemented "undo" functionality and storage of the application state, something that is a true pain to achieve without an underlying event plan.
If the benefits of this approach are not obvious to you yet, think of the following: The evolution of web design happened mainly via separation of different layers.
The other big plus of starting an application with an event plan is that you cut the big application down into manageable chunks and components and you can plan the detailed usability, information architecture and accessibility for each component separately. This allows you to develop in parallel with the design or information architecture team and results in reusable components for other applications.
January 17, 2007 at 9:57 am
Great article. It’s unfortunate that it may be missed (or not understood) by many people who are developing “HTML” applications.
I think there’s a step missing in your evolution, maybe 2 or 3 from the end. It’s the shift that occurs when you stop thinking about a web app as HTML decorated by Javascript, and instead realize that the Javascript IS the app, with HTML as
1) BODY: a set of pre-created DOM resources, and
2) HEAD: the wrapper for delivery of those resources along with CSS & JS
Once you’ve made this transition, it’s a lot easier to see compatibility with traditional (or even flash) app development. And sure, I guess then you can focus on events, just as most traditional programming environments have.
PS, while I’m here: Hire Jack Slocum, and pay him a lot of money. He’s your best evangelist.
January 17, 2007 at 1:04 pm
[...] Check out Event Driven Web Application Development over at the YUI blog [...]
January 17, 2007 at 2:34 pm
The demo link and download does not work
January 17, 2007 at 3:43 pm
@Tom (and others): Thanks for the note…my mistake. Fixed now. -Eric
January 17, 2007 at 7:49 pm
Great article Chris.
And just-in-time. I was thinking of the best way implement localication to my web app using Unobtrusive Object Oriented JavaScript and DOM.
Thanks for sharing your knowledge and experience.
Cheers.
January 17, 2007 at 7:50 pm
Links for January 17 and 18, 2007…
I’ll be adding more links this post throughout the day (erm … that day would be January 18, 2007).
Event-Driven Web Application Design
An overview of what to consider when developing interactive web applications with HTML and DOM scripting…
January 17, 2007 at 10:07 pm
Event driven programming (especially in the only-just-maturing environment of the web) is hard to debug because the events can occur in just about any order.
Christian’s suggestion of an Event plan is a good one – anything you can do to assist in minimising bugs and ensuring debugging of event code is easier is advised as they can be a major time-suck.
I’ve been following the Narrative Javascript project’s progress as it addresses these issues:
http://neilmix.com/narrativejs/doc/
I hope this project leads to future developments in the Javascript language itself (to avoid the compilation step if possible).
January 17, 2007 at 11:46 pm
[...] Christian Heilmann writes an interesting article about Event Driven Web Application Design over Yahoo UI. Christian starts the article with something I totally agree with: Frontend engineering rocks right now. The era of boring web sites is over and we’re all into pushing the envelope, erasing boundaries and getting beyond whatever prevents us from building the next killer web application. New companies building quick-turnaround web products spring up like mushrooms and many an old convention of web design is cast aside to make way for quick prototyping and agile development. [...]
January 18, 2007 at 4:56 am
A very good article, really helped me to grasp the concept of event driven applications. Too often we limit ourselves and try to ‘bodge’ our way through, rather than design and structure our applications in an event driven way. Hopefully developers will cotton on to this sooner rather than later and we will start seeing very powerful web applications that are useful.
January 18, 2007 at 9:03 am
Well-written, dig(g) it!
In an ideal design situation, you’d be able to attach endless numbers of event handlers to DOM elements without cost – but in development of the new Yahoo! Photos and similar to what Christian writes, we found that became very expensive in terms of looping through the number of items involved and assigning handlers, not to mention the memory required for these handlers.
Using an event delegation approach worked very nicely in our situation. Basically, we’d watch document.onmousedown and when it fired, would route the event to the object or item which it applied to (eg. a photo thumbnail.) While having many discrete handlers sounds ideal, the real-world implementation in the browser is usually a different story.
Steve: I like your theory on the shift in mindset – the BODY as pre-created DOM resources is more or less exactly how I look at it (in addition to providing the base data / degraded view)
January 18, 2007 at 9:37 am
You might be interested in a paper I presented at a W3C event on web applications a few years ago. It’s called A Standards-based Virtual Machine and argues for creating an application framework based on XHTML, XForms, XML Events, and so on. The main point is that the key to creating flexible ‘loosely-coupled’ web applications is defining all interfaces through events–much the same conclusion you have come to. :)
My company has been building exactly this framework, and it’s called Sidewinder. One of the things that we have done which is relevant to the discussion you’ve started here, is to use DOM 2 Events everywhere; not only to communicate within a DOM, but also across DOMs. For example, when multiple windows are created in Sidewinder (which is easy to do), one window can register for events in another. This means that one programming model–DOM 2 Events–is used for all application communication, not just that on web pages. (See, for an illustration, Bubbling events beyond the document boundary.
The longer-term plan is that this approach of using events to hold everything together should even include system events, such as “an email has arrived”. With such an event you could write applications that process email–perhaps categorising, forwarding, performing some task like putting food in the fish-tank, etc.–as easily as you can write any other XForms or JavaScript application.
It’s a very interesting approach, I feel, and it’s good to see it getting discussed. Thanks for a very enjoyable article!
All the best,
Mark Birbeck
CEO, x-port.net Ltd.
http://www.formsPlayer.com/
January 18, 2007 at 11:53 am
Good article, Chris. I’ve tended to apply these kinds of principles to web applications by the use of the State Machine model, drawing on my days writing real-time industrial control software and games (which from a programming perspective are, in their fundamentals, the same thing). In my experience, JavaScript as a language (whether in the browser or elsewhere) is ideally suited to an application architecture based on state transitions and delegation, due to its support for such delights as closures and higher-order functions. In fact, JS holds the same appeal to me as Forth, for many of the same reasons.
January 18, 2007 at 1:43 pm
I think it’s an interesting article, Yahoo! UI keeps revealing its secret to me on a daily basis now.
I believe however that you’re too critic about using frameworks to develop web applications.
Frameworks are very flexible, as you mentioned. But they don’t have to be extended, they have to b e better used. (Frameworks that aren’t extensible at the hand of their users should to be thrown in the garbage bin.)
The important thing to remember is that we’re not talking about two different approaches, we’re talking about PEOPLE that don’t know how to get more value for their buck.
I think your article would have been more interesting if it talked about people and not frameworks.
However, I do believe you’ve done a very good job at highlighting the problem.
January 18, 2007 at 3:31 pm
[...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: ajax development javascript toread web2.0 web webdev yui yahoo) [...]
January 18, 2007 at 5:52 pm
Christian, great article, sometimes you know things which you don’t realise you know. Minimising event listeners was a real eye opener for example. Indeed, yes, why hadn’t I seen that before. Will mimimise certain pages a lot.
January 18, 2007 at 11:26 pm
[...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: ajax blog development programming webdev javascript) [...]
January 20, 2007 at 5:15 pm
[...] Event-Driven Web Application Design Web standards are there to take the randomness out of web development and not to act as a policing tool. The main differentiator of a web application and a web site is that an app has much more interaction and is process-focused rather than content-driven (tags: WebDev Frameworks Events) [...]
January 21, 2007 at 5:51 am
[...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: toread javascript programming ajax) [...]
January 23, 2007 at 4:45 am
I wrote about something similar a couple of months ago at. http://www.frostinnovation.com/Blog.aspx (look for LazyHttp)
I think this will REALLY make it in a couple of years but at the moment I think it’s too immature and there’s too many browser isses (the biggeste being the MAX 2 simultanous open HTTP connections towards the same IP)
January 23, 2007 at 6:12 am
[...] Event-Driven Web Application Design [...]
January 26, 2007 at 7:29 am
[...] Event-Driven Web Application Design » Yahoo! User Interface Blog Designing exciting applications with events in mind (tags: design development javascript programming tutorial howto webdesign) [...]
January 26, 2007 at 8:53 am
[...] Interesting article on Web dev here though. [...]
January 31, 2007 at 10:04 pm
[...] Event-Driven Web Application Design [...]
February 2, 2007 at 9:36 am
Do you see much connection between what you are suggesting and Aspect Oriented Programming?
February 7, 2007 at 7:42 pm
[...] Another great post on the Yahoo! UI blog by Christian Heilmann, author of Beginning Javascript with DOM Scripting and Ajax. After you’re done reading the post, go here for a book excerpt. Bookmark to: [...]
February 23, 2007 at 2:05 pm
[...] Original post by Christian Heilmann and software by Elliott Back [...]
February 23, 2007 at 3:57 pm
[...] Original post by unknown and software by Elliott [...]
March 1, 2007 at 2:21 am
[...] Christian Heilmann is talking about Event-Driven Web Application Design on the YUI blog: The crux of the matter is that we don’t really yet understand how to build a real web application. We take tried and true methodologies that cover other development scenarios and try to shoe-horn them into something that helps us to achieve what we want on-time and within budget (and when was the last time that happened?). [...]
March 13, 2007 at 10:23 am
[WQD-139] Daily Journal thru 31-Mar-2007…
[2007-03-13] Friday, I started to extend the event handling. Before doing anything else with the PhoneBook, we should create an Event Plan (http://yuiblog.com/blog/2007/01/17/event-plan/) and create a set of Selenium tests. But, today, I’d like to get…
April 11, 2007 at 12:41 pm
[...] Christian Heillman makes a convincing case for one of the next evolutionary steps in front-end web programming – Event Driven Development [...]
May 8, 2007 at 2:40 am
[...] More on Event-Driven Web Application Design by Christian Heilmann is talking about Posted by Muthu on May 08 2007 under Web Technologies, AJAX, DOM, JavaScript [...]
August 20, 2007 at 8:49 am
I’ve just started my career as a web designer and this article is very useful for me I think. Thanks.
September 4, 2007 at 11:36 am
[...] the list I noticed that many great tutorials were actually published on this Blog, including the Event-Driven Web Application Design and many good screencasts, definitely worth a try, even if you don’t use YUI! [...]
September 13, 2007 at 2:53 pm
[...] have been many influential articles about event-driven programming within the web browser, and developers are increasingly using this technique. But there is room to push the approach even [...]
September 30, 2007 at 10:54 pm
A very good article. Do you have more information/examples for YUI and its Custom Event Object?
October 16, 2007 at 12:02 pm
I’m trying to understand the benefits of creating these Custom Events on parent nodes instead of just dynamically adding events to all the children nodes. So why, for instance, is the above construct better than something like this? (using jquery syntax for my example):
$('#languages a').click(function(){var lang = t.href.replace(/.*?lang=/,"); changeLanguage(lang);});
function changeLanguage(lang) {
... page methods...
}
October 16, 2007 at 7:11 pm
ok lesson learned: don’t post comments until you’ve done your homework :)
a few tips for any newbie (like me) reading this article and sort of understanding but not fully grasping the concepts.
i took away two points from this, but not until I had some more context about each:
point 1: YUI custom events allow you to make other events fire when your ‘custom’ function is triggered (ie. your functions can be aware of when other functions are executed and act accordingly)
context: YUI’s custom event example (http://developer.yahoo.com/yui/examples/event/custom-event.html)
point 2: using event delegation (ie. only adding listeners to root nodes instead of each child) is much faster (memory-wise) because it doesn’t have to iterate through every single node. event delegation also allows dynamically created elements to inherit handlers from its parent node, which ‘event handling’ can’t do.
context: the event delegation article linked above (http://icant.co.uk/sandbox/eventdelegation/)
so read those two articles to help understand the broader concepts here.
November 12, 2007 at 12:01 am
[...] Event-Driven Web Application Design » Yahoo! User Interface Blog [...]
November 14, 2007 at 1:24 am
[...] Event-Driven Web Application Design The Bubbling Technique & Custom Event, YUI’s Secret Weapon by Caridy Patiño [...]
November 15, 2007 at 8:55 pm
[...] Event Driven JavaScript Application Design [...]
November 27, 2007 at 12:38 am
The crux of the matter is that we don’t really yet understand how to build a real web application. We take tried and true methodologies that cover other development scenarios and try to shoe-horn them into something that helps us to achieve what we want on-time and within budget.
December 19, 2007 at 4:46 pm
[...] your Controls and listened to by any other javascript function. This allows you to put in practice Event-Driven Development in a simple, lightweight [...]
January 25, 2008 at 4:19 am
Dear Christian, after reading you other blogs i am sure your an enthusiastic developer. I really appreciate your work. Let’s push things forward, and thanks for another interesting article.
March 6, 2008 at 6:46 am
Christian,
Great article. Like Nick, we’ve started to use the State Machine model in some of our front end work. However, this was before we’d investigated YUI, knowing about the custom event object would have made our lives a little easier!
April 22, 2008 at 2:17 pm
[...] been talking about event driven application design in JavaScript in January last year and inspired Caridy Patiño to write his Bubbling Library based on these [...]
April 23, 2008 at 4:58 pm
Great article! Having a number of self-contained components that subscribe to a list of events is a great way to keep code clean and maintain a large, complicated web application.
By describing all possible events that can occur in the application (users taking action, or events triggered by other things like an Ajax request returning), and then subscribing individual components (essentially registering event listener functions), problems with application state rarely occur and debugging becomes much easier.
With a tightly-coupled web application where each component depends on interlinking chains of data, walking through the code can be a nightmare. But as long as you follow practices like this to decouple the code, it’s possible to keep the JavaScript very clean, readable and editable even at immense sizes and levels of complexity.
April 24, 2008 at 1:50 am
[...] Event Driven JavaScript by Christian Heilmann [...]
May 29, 2008 at 6:30 am
[...] Event-Driven Web Application Design – Yahoo! User Interface Blog (tags: ajax architecture web_dev blogs) [...]
October 7, 2008 at 10:29 am
The regex in eventTriggers.js is a bit ambigious.
*? attempts non-greedy matching, but in the case that the character to match is ‘.’ the non-greedy match will be equivalent to the slightly simpler greedy match ‘.*’
March 15, 2011 at 7:39 am
[...] – Christian Heilmann in Event-Driven Web Application Design [...]