Event-Driven Web Application Design

By YUI TeamJanuary 17th, 2007

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:

  • You either use a framework (like Ruby on Rails, Spring or Microsoft .NET) to build your web-app or
  • You build your web app with best-practices ideas coming from more traditional web design and/or application design.

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.

A Problem of Approach

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 framework approach relies on a silver bullet and approaches web development with fat-client application ideals from higher programming languages like Java or C++. This does not take into consideration the fact that web development is a discipline that operates with great uncertainties regarding the nature of client-side hardware and software. Optimization has to be for the user and not for the developer (although these don’t necessarily have to be mutually exclusive).
  • The web standards approach would not be a problem at all if people would follow standards with the goal of making things easier by following an agreed approach and not see following the words of the W3C to the last detail as the only way to do things. Web standards are there to take the randomness out of web development and not to act as a policing tool.

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.

Understanding Events

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:

  • Something happens to an element, to the main document, or to the browser window and that event triggers a reaction. For example, the window finishes loading and on that event we start an initialization method; or the user clicks a link and we use that event to trigger another function.

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:

  • Something happens; an event occurs.
  • The investigation begins what element was activated and how. This happens by questioning each element from the window to the body to the first child node and so on until the element that was activated, the event target, is reached. This is called event capturing.
  • When the element is reached, the process of reporting goes back up through the DOM right back up to the window. This is called event bubbling.
  • You can intercept events on both legs of this journey at any time by adding event listeners to either the window or any of the objects that get queried. Event listeners define what event to look out for (click, keypress, load, mousedown…), the object to which the handler should be applied, and what method to call when it happens.
  • You can stop events from going back up to the window by calling a cancelEvent() method and you can retrieve the object the event occurred on, the event target, with a helper method called getTarget().
  • You can add as many listeners waiting for as many different events and each calling as many methods as you like.

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.

Planning an Event-Driven Application

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:

  • Application is loaded
    • Initialize the stage
    • Get the locale
    • Load extra content
    • Load adverts
    • Display stage
  • User changes language by activating a language component
    • Load extra content
    • Load adverts
    • Display Stage

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.

Beyond DOM Events: The Custom Event

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.

A Quick Example of an Event-Plan Driven Application

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).

eventPlanExample.html (excerpt):

  <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>
  <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>

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');

// Changing the layout
  layoutChange = new YAHOO.util.CustomEvent('layout change');


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){

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);
    document.getElementById('output').innerHTML = ''; 
    var lang = t.href.replace(/.*?lang=/,'');

function changeLayout(e){
  var t=YAHOO.util.Event.getTarget(e);
    document.getElementById('output').innerHTML = ''; 
    var lang = t.href.replace(/.*?layout=/,'');
YAHOO.util.Event.onAvailable('languages', initLanguages);  
YAHOO.util.Event.onAvailable('layout', initLayout);

You can download the demo or try it out for yourself.

The Key Differentiator and Where This Can Go

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.

Event-Driven Web Application Design as an Evolutionary Step

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.

  • When we created the first web applications connection speeds were slow and being connected to the internet cost us money by the minute.
  • Therefore we used frames to only load what has changed in the app. This led to the problem that if one frame didn’t load properly the app didn’t work and users were forced to reload the parent page.
  • The next problem was that browsers didn’t support CSS and we used tables and font tags to define the look and feel which made it hard to change them and the documents themselves rather heavy.
  • When CSS support became more consistent and usable, we were able to get rid of the extra HTML, documents got lighter and we could get rid of the frames again.
  • The next problem we encountered was that mixing backend logic and HTML output was problematic for maintenance (maintainers needed both skills). As a result, we came up with templating languages that allowed for separation of server-side logic and the structure of the interface.
  • Right now we still see the browser or the framework capabilities as the boundary of our applications. This is a pragmatic approach but limits us in our creativity and binds the application planning and documentation to browsers as the means of display.
  • However, if we take events — including both DOM events and Custom Events — as the main consideration when planning the application we can free ourselves of these limitations and become a lot more independent of the technology in use.
  • An application developed with an underlying Event Plan could be easily shifted to another technology like Flash or become a plug-in for thick clients like instant messengers or even operating systems.

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.


  1. 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.

  2. [...] Check out Event Driven Web Application Development over at the YUI blog [...]

  3. The demo link and download does not work

  4. @Tom (and others): Thanks for the note…my mistake. Fixed now. -Eric

  5. 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.


  6. 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…

  7. 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:


    I hope this project leads to future developments in the Javascript language itself (to avoid the compilation step if possible).

  8. [...] 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. [...]

  9. 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.

  10. 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)

  11. 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.

  12. 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.

  13. 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.

  14. [...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: ajax development javascript toread web2.0 web webdev yui yahoo) [...]

  15. 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.

  16. [...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: ajax blog development programming webdev javascript) [...]

  17. [...] 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) [...]

  18. [...] Event-Driven Web Application Design » Yahoo! User Interface Blog (tags: toread javascript programming ajax) [...]

  19. 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)

  20. [...] Event-Driven Web Application Design » Yahoo! User Interface Blog Designing exciting applications with events in mind (tags: design development javascript programming tutorial howto webdesign) [...]

  21. Do you see much connection between what you are suggesting and Aspect Oriented Programming?

  22. [...] 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:                 [...]

  23. [...] Original post by Christian Heilmann and software by Elliott Back [...]

  24. [...] 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?). [...]

  25. [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…

  26. [...] Christian Heillman makes a convincing case for one of the next evolutionary steps in front-end web programming – Event Driven Development [...]

  27. [...] 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 [...]

  28. I’ve just started my career as a web designer and this article is very useful for me I think. Thanks.

  29. [...] 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! [...]

  30. [...] 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 [...]

  31. A very good article. Do you have more information/examples for YUI and its Custom Event Object?

  32. 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...


  33. 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.

  34. [...] Event-Driven Web Application Design » Yahoo! User Interface Blog [...]

  35. [...] Event-Driven Web Application Design The Bubbling Technique & Custom Event, YUI’s Secret Weapon by Caridy Patiño [...]

  36. [...] Event Driven JavaScript Application Design [...]

  37. 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.

  38. [...] your Controls and listened to by any other javascript function. This allows you to put in practice Event-Driven Development in a simple, lightweight [...]

  39. 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.

  40. 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!

  41. [...] 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 [...]

  42. 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.

  43. [...] Event Driven JavaScript by Christian Heilmann [...]

  44. [...] Event-Driven Web Application Design – Yahoo! User Interface Blog (tags: ajax architecture web_dev blogs) [...]

  45. 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 ‘.*’

  46. [...] – Christian Heilmann in Event-Driven Web Application Design [...]