Sneaky Abstractions

Subscribe to my Feed, follow me on , recommend me on Working With Rails or see my code on GitHub

Decoupling event handlers

Posted on July 01, 2008 10:26 Tagged with javascript, events.

Have you ever wondered how you can “fire” an event on an element that you’ve attached a listener to, so you can implicitly perform that action? I know I have, but I don’t anymore, because it taught me a lesson: The action performed (a function) when an event happens on an element should be decoupled from the actual event. We all know that coupling is bad, so how do you decouple something like this, for example?

$('add_new_text_field').observe(function(e){
  e.stop();
  var form = e.up('form');
  var input = new Element('input', {type:'text',name:'something'});
  form.insert({bottom:input});
});

Well, it’s easy! Just identify what the action performed by the handler is, and separate it from the handler. In this case, it’s adding a new text field to a form. In the example above, the action is part of the handler for the element with the id “add_new_text_field”. If you want to re-use this functionality, you’re out of luck.

The action, extracted and decoupled from the handler, looks like this:

function addNewTextField(form){
  var input = new Element('input', {type:'text',name:'something'});
  form.insert({bottom:input});
}

Now, the event handler is much simpler:

$('add_new_text_field').observe(function(e){
  e.stop();
  addNewTextField(e.target.up('form'));
});

And you can re-use the action in another handler! Don’t you just love anonymous functions?

This is your first class ticket to high speed action and you're in the driver's seat