Sunday, March 2, 2014

jQuery remove and restore element events

jsFiddle Link

function toggleEvent(id) {
    var target = $(id);
    var events = $._data(target[0], 'events');
    if(events!=undefined){    //  if the element has event || target = element
        target[0].event_name = [];
        target[0].event_handler = [];        
        $.each(events, function(event_name, event_handler) {
            target[0].event_name.push(event_name);
            var _handlers=[];
            for(var i=0;i<event_handler.length;i++){
                _handlers.push(event_handler[i].handler);
            }
            target[0].event_handler.push(_handlers);          
        });  //store the events
        target.off();  // delete the events
    }else{    // has the elment no event
        for(var i=0; i < target[0].event_handler.length; i++){
            for(var ii=0;ii<target[0].event_handler[i].length;ii++){
                target.on(target[0].event_name[i], target[0].event_handler[i][ii]);
            }          
        }  // re-store the events
        target[0].event_name = [];
        target[0].event_handler = [];  //reset
    }
}

$("#a").click(function() {
    alert("Event in action");
});

var eventInAction = true;
$("#b").click(function(){
    toggleEvent('#a');
    if(eventInAction) {
        eventInAction = false;
        $(this).html("Add events to button 'A'");
    } else {
        eventInAction = true;
        $(this).html("Remove events from button 'A'");
    }
});

No comments:

Post a Comment