Thursday, January 13, 2011

Advanced Event Handling in JavaScript - Dynamic Event Registration Models

In this post, we will try to talk about dynamic event registration models in Java Script.

There are many ways to attach event handlers in JavaScript.
Actually, Event handlers is the function.
 Functions are objects in JavaScript. So it can be manipulated and passed around just like any other object.

In this way, Just assign the function to the event that you want to involve. Assign null to remove it back.
Please note, setAttribute method does not work in IE.

function AttachEvent(attach){
    if(attach){
        document.getElementById('buttonDelete').onclick = confirmDelete;
        //Doesn't work in IE
        document.getElementById('buttonDelete2').setAttribute('onclick', 'confirmDelete()');
    }
    else{
        document.getElementById('buttonDelete').onclick = null;
        document.getElementById('buttonDelete2').onclick = null;
    }
}

function confirmDelete(){
    return confirm('Are you sure you want to delete?');
}


<input type="checkbox" id="chkConfirm" onclick="AttachEventSampleOne(this.checked)"/>Confirm before delete
<input type="button" id="buttonDelete" value="Delete" />
<input type="button" id="buttonDelete2" value="Delete 2" /><br/>

  
Sample Two: Function by manipulating strings

In this way, you can select a function from predefined functions by manipulation the string. Assign the null to remove it back.

function AttachEventSampleTwo(sender){      
     
    if(sender.checked){
        var msg = sender.value + ' was selected.';
        var functionToCall =  'click_' + sender.id + '("' + msg + '")';          
        document.getElementById('buttonSampleTwo').onclick = new Function(functionToCall);
    }
    else
        document.getElementById('buttonSampleTwo').onclick = null;
         
}
     
function click_mySampleTwoEvent1(msg){
    alert('Sample Two Event 1 : ' + msg);
}

function click_mySampleTwoEvent2(msg){
    alert('Sample Two Event 2 : ' + msg);
}
    
<input type="radio" id="mySampleTwoEvent1" name="SampleTwo" onclick="AttachEventSampleTwo(this)" value="Event One" />Event One
<input type="radio" id="mySampleTwoEvent2" name="SampleTwo" onclick="AttachEventSampleTwo(this)" value="Event Two" />Event Two    
<input type="button" id="buttonSampleTwo" value="click" /><br/>

Sample Three: Multiple Events and Hardcoded Functions

In this way, you can add more than one event handlers for a certain event.
Please note: addEventListener and removeEventListener is for non-IE browsers and attachEvent and detachEvent is for IE.

function AttachEventSampleThree(sender,functionToCall){

    var ctrl = document.getElementById('buttonSampleThree');
     
    if(sender.checked){
        if(ctrl.addEventListener)
            ctrl.addEventListener('click',functionToCall,false);
        else if(ctrl.attachEvent)
            ctrl.attachEvent('onclick',functionToCall);
    }
    else{       
        if(ctrl.removeEventListener)
            ctrl.removeEventListener('click',functionToCall,false);
        else if(ctrl.detachEvent)
            ctrl.detachEvent('onclick',functionToCall);
    }
}

function SampleThreeEventOne(){
    alert('Sample Three: Event One');
}
  
function SampleThreeEventTwo(){
    alert('Sample Three: Event Two');
}
<input type="checkbox" id="chkSample3Event1" onclick="AttachEventSampleThree(this,SampleThreeEventOne)"/>Event One        
<input type="checkbox" id="chkSample3Event2" onclick="AttachEventSampleThree(this,SampleThreeEventTwo)"/>Event Two        
<input type="button" id="buttonSampleThree" value="Fire" /><br/>

Sample Four: Multiple Events and Variable Functions

This way is same as sample three except function name is builded by string manipulating
var eventHandlers = new Array();

function AttachEventSampleFour(sender){

    var ctrl = document.getElementById('buttonSampleFour');
    var msg = sender.id + ' was checked.';
    var key = sender.id;
    var dynFunction =  sender.id + '("' + msg + '")';
     
    if(eventHandlers[key]==undefined || eventHandlers[key]==null)
        eventHandlers[key] = new Function(dynFunction);
             
    if(sender.checked){
        if(ctrl.addEventListener)
            ctrl.addEventListener('click',eventHandlers[key],false);
        else if(ctrl.attachEvent)
            ctrl.attachEvent('onclick',eventHandlers[key]);
    }
    else{       
        if(ctrl.removeEventListener)
            ctrl.removeEventListener('click',eventHandlers[key],false);
        else if(ctrl.detachEvent)
            ctrl.detachEvent('onclick',eventHandlers[key]); 
                     
        eventHandlers[key] = null;
    }   
     
}

function chkSampleFourEventOne(msg){
    alert('Event One: ' + msg);
}

function chkSampleFourEventTwo(msg){
    alert('Event Two: ' + msg);
}
<input type="checkbox" id="SampleFourEventOne" onclick="AttachEventSampleFour(this)" />Event One        
<input type="checkbox" id="SampleFourEventTwo" onclick="AttachEventSampleFour(this)"/>Event Two        
<input type="button" id="buttonSampleFour" value="Fire" /><br/>

No comments:

Post a Comment

subversion video