May 26 2007

Define Custom EventArgs in AJAX 1.0 Extensions

Category: AJAX-ATLASBil@l @ 15:47

While preparing a sample application to my new article on that will be published soon on Creating Client Controls in ASP.NET 2.0 AJAX 1.0 Extensions, I had to bind an event handler to a button created in the render method of the control. Usually, event handlers are called with an empty argument which is of type Sys.EventArgs. However, to fire an event handler and pass in a parameter instead of the empty EventArgs, you use something similar to:

$addHandler(btn, 'click', Function.createCallback(this._clickDelegate, "MyData")); 

In the above line of code, you use the Function.createCallback function when you want to pass in some data instead of the empty EventArgs default class. In this case, we are passing a string that has the value of "MyData".

Another better and clean approach is to define a new custom EventArgs class. This way, you will feel yourself while developing in AJAX Client Side as if you are working with ASP.NET Servrer side. The class that I will define is the ContactEventArgs class which is as follows:


Bhaidar.AJAXComponents.ContactEventArgs= function(data) {
    this._data = data;

Bhaidar.AJAXComponents.ContactEventArgs.prototype= {
    get_data: function() {
        return this._data;
    set_data: function(value) {
        this._data = value;

Bhaidar.AJAXComponents.ContactEventArgs.registerClass('Bhaidar.AJAXComponents.ContactEventArgs', Sys.EventArgs);

The class is very simply, I simply add a property called data to hold the data that are needed to be passed. The important thing to mention in defining this class is the following two lines:

Bhaidar.AJAXComponents.ContactEventArgs.registerClass('Bhaidar.AJAXComponents.ContactEventArgs', Sys.EventArgs);

The first calls the constructor of the base class and in the second line you specify that this class inherits from the EventArgs class.

Now attaching a handler and passing some data can be done this way:

        var contactEventArgs = new Bhaidar.AJAXComponents.ContactEventArgs();
        $addHandler(btn, 'click', Function.createCallback(this._clickDelegate, contactEventArgs));

Isn't that clean and clear?

Hope this helps,




Comments are closed