31 July, 2010

Delegate in Javascript

Before going to the topic, lets know brief about "Delegate":
A delegate is like a function pointer, which stores reference of a method. It specifies a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners.

We can create and define delegates in Javascript to perform some specific tasks on an object. The following is the code to define delegate.

function CreateDelegate(contextObject, delegateMethod)
return function()
return delegateMethod.apply(contextObject, arguments);

Let us take a simple example and use the delegate in that. Here is the scenario, there is a large image to be loaded on a web page and we need to display the height and width of that image after loading. Delegate method will be very handy in this situation.

var image = new Image();
image.src = "test.jpg";
image.onload = CreateDelegate(image, ImageLoaded);

function ImageLoaded()
alert(this.width +" X "+ this.height);

We are creating a delegate on image loaded event, which will call method 'ImageLoaded'. This delegate automatically pass the object on which the delegate is defined, to the method. We can refer the actual image object using 'this' in the method.

No comments:

Post a Comment