• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Event Handlers and Callback Functions in JavaScript

By Sjoerd Visscher | on Aug 19, 2006 | 2 Comments
JavaScript Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

Introduction

In Higher Order Programming in Javascript I discussed the various ways of using functions as values. One particular trick in that document caught the attention of Dan Shappir, who pointed out to me: "your technique shows how JavaScript supported delegates all along, so this is not some great C#/.NET invention." While searching for some more information about these delegates, I found out that Microsoft has added them to Visual J++ too, invoking an interesting response from Sun, where it’s discussed how delegates can much better be implemented with Inner Classes. As this is aparently a hot issue in other languages, and because event handlers and callbacks are useful in webpages too, I decided to write a new article to discuss this.

The Trick

The problem is as follows: Methods use this to refer to the object it is a method of. But, when using a method as event handler or callback function, this does no longer point to that object. The trick is to use the closure like behaviour of functions, so that the method will always have access to it’s object.

Let’s look at an example: We want to use a method of an Alerter class as an event handler.

function Alerter(text) {

this.text=text;
var me=this;
this.invoke=function () {
alert(me.text);
}
}

var sayHi=new Alerter('Hello, world!');
div.attachEvent('onclick', sayHi.invoke);

So, instead of using this, we use a variable me, that equals this when the invoke method is created. And, in contrast to this, me will keep refering to the correct Alerter object, even when it’s passed as a function to the attachEvent method of an HTML element.

Higher Order Programming again

window.setTimeout is an often used function for dynamic webpages. It waits for a given amount of time, and then calls a callback function. The above defined sayHi function can be used as a callback function: setTimeout(sayHi.invoke,2000) will show an alert box after 2 seconds. But what if we want to be extra cool and show 2 alert boxes after those 2 seconds? Then we’d have to create a new function that calls both Alerter objects:

var sayHi=new Alerter('Hello, world!');  

var sayBye=new Alerter('Bye, world!');
setTimeout(function() {sayHi.invoke();sayBye.invoke();},2000);

A nice feature of Microsoft’s delegates is that you can create a single composite deligate from several delegates. It looks less messy than inserting an anonymous function. Let’s do that in Javascript too, by extending the function prototype.

Function.prototype.andThen=function(g) {

var f=this;
return function() {
f();g();
}
};

Now we can write:

setTimeout((sayHi.invoke).andThen(sayBye.invoke),2000);

Several callbacks

With the andThen method, it becomes very easy to create an object that allows several other objects to register callbacks.

function Manager() {

this.callback=function () {}; // do nothing
this.registerCallback=function(callbackFunction) {
this.callback=(this.callback).andThen(callbackFunction);
}
}

var manager=new Manager();
manager.registerCallback(sayHi.invoke);
manager.registerCallback(sayBye.invoke);
manager.callback();

Conclusion

With a simple technique event handlers and callback functions become a lot more interesting in Javascript. As Dan Shappir pointed this out to me, just this morning (after which I started to write the article), I can’t wait to try more of this. I hope you can’t too, and if you’ve got something to show, don’t hesitate to contact me.

Share this story:
  • tweet

Author Description

 

2 Responses to “Event Handlers and Callback Functions in JavaScript”

  1. November 11, 2010

    Prakash Log in to Reply

    Its very useful.. Thanks

    • November 12, 2010

      Anonymous Log in to Reply

      approved

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,239Followers 494Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.