Event Handling in SproutCore 1.0 – Part 1

written by SproutCore

SproutCore is one of the first JavaScript frameworks to implement event delegation throughout the entire framework.  In this series of blog posts I’m going to explain a bit about how event delegation works and how you use it to handle events in SproutCore Views.

For starters, let’s talk about what event delegation is and how its handled in SproutCore.

What is Event Delegation?

Event delegation is a much faster and simpler way of handling events.  Rather than register listeners for every DOM event you might be interested in on a page, SproutCore delegates responsibility for handling events to just six listeners added to the window and document objects.  These listeners take responsibility for calling any Views that are interested in any event that comes in.

Take the simple example shown below.  This diagram shows a simple document with a button.  When you press the mousedown on the button, it calls a method on a corresponding “View” object in JavaScript:

Regular Delegation

So how does this look with event delegation?

In SproutCore, the object that receives delegated events is called the RootResponder.  (You can find it in your running app at SC.RootResponder.responder).  The RootResponder listens for a mousedown event on the document object.  When this event occurs, the browser will fill in a target property on the event to tell you which DOM element received the event.  The RootResponder uses this property to determine which view should actually be notified of the event, in this case the button view.

Continue reading