Using Client-Side Custom Events in ASP.NET Applications

Download Code

These days many average developers like me find themselves breaking their heads to implement 'desktop like' behaviors for web applications. Many ASP.NET controls (like Button and ModalPopupExtender) have public properties for attaching javascript handlers to client side events. Now a common problem is,
"you want to notify multiple controls about an client side event."
For example:
  • When value inside some control of a grid changes , sum and average needs to be calculated and displayed.
  • You may want to perform validation and few calculation on 'click' event of an ASP.NET 'button' control.
In more complex scenarios, it might be required to be able to dynamically add and remove handlers, in addition to things mentioned above. I have seen developers do lot of ugly 'wiring' of javascript functions to achieve this. Of course it works , but it is a nightmare to maintain. In this article we will see how to make use of 'client-side custom events to simplify coding for such scenarios.

What are 'Client-Side Custom events' ?

DOM elements have some standard events defined, like 'click, onmouseover,onblur..etc' . But what if we wanted to define new event that didn't exist and use them (just like we do in C# ). The answer to this is 'custom events'. There are many javascript libraries which make it possible to create and use custom events. In this article I will use jQuery, since it is believed to be supported in next version of Visual Studio. Custom events are similar to once we use in C# or VB.NET coding. We basically think of an event name, attach one or more handlers to this event and raise the event whenever required.

Sample Scenario

I have taken up a very simple scenario, where I will show how use of custom events make things pretty as opposed to tradition methods. I have a grid like display , where each row performs a specific operation on value input by the user using a AJAX modal popup. Attached below is the screen shot. When the user brings up the modal dialog box , enters value and clicks 'OK' following things happen:
  • Input is validated.
  • In first row results of the operation : value * 2 is displayed.
  • In first row results of the operation : value + 2 is displayed.
  • In first row results of the operation : value / 2 is displayed.
Screenshot of the sample application. Doesn't look like a big deal ! So why use custom events, when it is lot easier to write a single function to do all this, and hook it up to 'OnOkScript' property of the ModalPopupExtender. We could do that , but what if , we had 20 such operation ? wont a single function be too long and complex ? And what if we wanted the ability to add/remove handlers dynamically? In the above screen , I have placed checkboxes to facilitate dynamic attaching /detaching of handlers.

Using Custom Events

For the above scenario, I thought of an custom event named 'okbuttonpressed' . To the 'OnOkScript' property of the modalpopupextender, we assign the 'GetNumber()' javascript function. Given below is the code:
<ajaxToolkit:ModalPopupExtender PopupControlID="Panel1" ID="ModalPopupExtender1" runat="server" 
            TargetControlID="Button1" CancelControlID="btnCancel" OkControlID="btnOK" 
            BackgroundCssClass="modalBackground" OnOkScript="GetNumber();" >
 function GetNumber()
    {  
        var i = $("#txtVal")[0].value;
        var val = parseInt(i);
        if( val != i)
        {alert("Please enter a valid integer.");$("#txtVal")[0].value=0;}
         else
         { jQuery(document).trigger('okbuttonpressed', val);}
    }
Here , 'txtVal' is id of a texbox inside the modal popup where user enters a value. As a best practice, I should have tried to fetch 'ClientId' (since its a severside control) and use it, but since we are not dealing with repeaters and usercontrols , I am using the id directly (also because I am bit lazy). So when 'OK' button is clicked , the above function gets called and the 'okbuttonpressed' custom event gets triggered.

Attaching handlers to custom events

On check/uncheck of a checkbox in any row, I have written code to attach /detach a handler for the custom event 'okbuttonpressed' . For example, when 'chkAdd' is selected, we attach a handler 'AddVals' . Here is complete code:
  hkAdd.Attributes.Add("onclick", "AddChkChanged(this)");
  chkMul.Attributes.Add("onclick", "MulChkChanged(this)");
  chkDivide.Attributes.Add("onclick", "DivChkChanged(this)");
      function DivChkChanged(x)
    {
        if(x.checked)
             jQuery(document).bind('okbuttonpressed', DivVals);         
        else
              jQuery(document).unbind('okbuttonpressed', DivVals);
    }
    
    function MulChkChanged(x)
    {
        if(x.checked)
             jQuery(document).bind('okbuttonpressed', MulVals);         
        else
              jQuery(document).unbind('okbuttonpressed', MulVals);
    }
    
    function AddChkChanged(x)
    {
        if(x.checked)
             jQuery(document).bind('okbuttonpressed', AddVals);         
        else
              jQuery(document).unbind('okbuttonpressed', AddVals);
    }
Thats all ! Now if you run the page, you can see for yourself how the custom events work. Be sure to check any of the checkboxes, before brining up the modal popup to see calculated result. Thats all from me. Though this was a very simple example, the attempt was to illustrate how using 'custom events' can help in clean coding. Without them our javascript would have been inelegant and full of 'if' statements and global variables. Custom events are much more useful when dealing with more complex scenarios. They pave the way for better event driven programming in javascript.


Copyright (c) 2007-2013 Ashish Patil . Please read FAQ for more details.

comments powered by Disqus