Delegate in Javascript

March 19th, 2008   Filed Under Javascript, Tips & Tricks, browser, gyan, prototype, snippet  

I was just remembering my C#.net days and the concept of delegates, which I think Java doesn’t support natively[please comment if someone knows java does].

So, I thought of sharing my view and the way we can mimic delgates in Javascript to work with HTML.

First let me explain the concept of delegate if someone doesn’t know. A delegate is a function pointer which allows the programmer to encapsulate a reference to a method inside a delegate object. If that was too technical, let me tell you in plain english that a delegate is an object which can call the referenced methods to a procedure where it has been passed.

Before going further, let me put some code here. Just go through it and I will explain what is it.

var _delegate = {};
_delegate.items = [];
_delegate.push = function(f){_delegate.items.push(f)};
_delegate.exe = function()
{
 for(di=0; di<_delegate.items.length; di++)
 {
  _delegate.items[di]();
 }
}

In the above code, you can see, the first line declares an object called delegate. The second line has a member called “items”(to be used internally) and two methods called “push” and “exe”.

Where can you use it:
You can use it for a page load event where you are not always sure what are all the functions you need to execute for different pages. So, you have a generic function which gets called upon every page loads. And what you need to do is just “push” the function name as many times you want in your whole page, js files etc.

But onload sucks:
Yeah, that’s true. So you need a DOMReady event for each page, so that everything executes as soon as the DOM is available.

Using the Delegate:
Now for using your delegate you need to include the DOMReady first. Then you can use the delegates as shown:

_delegate.push(fn1);// you add your first function handle
_delegate.push(fn2);// you add your second function handle
DOMReady(_delegate.exe); // this doesn't change ever

And, when your DOM is ready, all the pushed functions are fired. You must, be thinking - “What’s the big deal?” The big deal is your clean approach to onload execution. In conjunction with DOMReady, you have the easiness of globally having the _delegate object to push at any part of your code.

This is not the only use of delegates. You can have a delegate for any function call, but for that you need to create a constructor rather than a global delegate object. And globally speaking, that would be the better way to use the concept as you would create a new object and then use it. If you want to know that in detail, ask me how.

Please comment your thoughts about this, and let me know if you have a say. Thanks for your time!!