Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress jQuery event handling temporarily

Tags:

Is there an elegant way to temporarily suppress jQuery events? I use code like this:

$(element).unbind(event, function1).unbind(event, function2);
// code for which the event is suppressed
$(element).bind(event, function1).bind(event, function2);

but I find it a bit clumsy and not very scalable to many events. Why do I want to suppress events temporarily? I use BlockUI plugin to block UI during Ajax access. This is done with: $().ajaxStart($.blockUI).ajaxStop($.unblockUI) as proposed by BlockUI.

However, one Ajax access is special, so I need a different message. The ajaxStart and ajaxStop events interfere with the message code (nothing is shown):

function message(text, callback) {
  if (text == undefined) {
     $.unblockUI();
     return;
  }

  // $().unbind('ajaxStop', $.unblockUI).unbind('ajaxStart', $.blockUI);
  $("#message_text").html(text);
  $.blockUI({message: $("#message")});
  $("#message_ok").click(function() { 
    // $().bind('ajaxStop', $.unblockUI).bind('ajaxStart', $.blockUI);
    $.unblockUI();
    if (callback != undefined) callback();
  });
}

Only if I uncomment the unbind() and the bind() lines, it is working.

like image 958
nalply Avatar asked Nov 27 '09 15:11

nalply


People also ask

How to unbind event jQuery?

jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.

How do I turn off event listener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

Which jQuery function removes previously attached event handlers on the element?

The . off() method removes event handlers that were attached with .


2 Answers

I realize this question is old, but I found it while seeking an answer to the same question, and ended up finding a different solution that works well in simple applications of event handlers.

$(element).click(function(e) {
  e.preventDefault();

  // Check for fired class
  if ($(this).hasClass('fired') == false) {
     // Add fired class to all instances of element
     $(element).addClass('fired');

     // Do the rest of the function...

     // Remove fired class to 'reactivate' events
     $(element).removeClass('fired');   
  }
}

Simply adding a class to your 'element's while the code from the event is firing allows you to prevent further code from being executed as the result of another click event. So while you're not actually preventing any other click events, you're preventing the resulting code from running. Simple, crude, ignores the heavily preached use of bind and unbind, but works.

like image 199
Eric Avatar answered Sep 23 '22 09:09

Eric


cost me finish this script, I hope it's useful:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/javascript">
$(function(){

    //ini plugin

    jQuery.event.freezeEvents = function(elem) {

        if (typeof(jQuery._funcFreeze)=="undefined")
            jQuery._funcFreeze = [];

        if (typeof(jQuery._funcNull)=="undefined")
            jQuery._funcNull = function(){ };

        // don't do events on text and comment nodes
        if ( elem.nodeType == 3 || elem.nodeType == 8 )
            return;

        var events = jQuery.data(elem, "events"), ret, index;

        if ( events ) {

            for ( var type in events )
            {
                if ( events[type] ) {

                    var namespaces = type.split(".");
                    type = namespaces.shift();
                    var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

                    for ( var handle in events[type] )
                        if ( namespace.test(events[type][handle].type) ){
                            if (events[type][handle] != jQuery._funcNull){
                                jQuery._funcFreeze["events_freeze_" + handle] = events[type][handle];
                                events[type][handle] = jQuery._funcNull;
                            }
                        }
                }

            }
        }
    }

    jQuery.event.unFreezeEvents = function(elem) {

        // don't do events on text and comment nodes
        if ( elem.nodeType == 3 || elem.nodeType == 8 )
            return;

        var events = jQuery.data(elem, "events"), ret, index;

        if ( events ) {

            for ( var type in events )
            {
                if ( events[type] ) {

                    var namespaces = type.split(".");
                    type = namespaces.shift();

                    for ( var handle in events[type] )
                        if (events[type][handle]==jQuery._funcNull)
                            events[type][handle] = jQuery._funcFreeze["events_freeze_" + handle];

                }
            }
        }
    }

    jQuery.fn.freezeEvents = function() {

        return this.each(function(){
            jQuery.event.freezeEvents(this);
        });

    };

    jQuery.fn.unFreezeEvents = function() {

        return this.each(function(){
            jQuery.event.unFreezeEvents(this);
        });

    };

    //end plugin

    jQuery("#test1").ajaxStart(function test1(){
        jQuery("#result").append('test1 ajaxStop<br>');
    });

    jQuery("#test1").ajaxStop(function test2(){
        jQuery("#result").append('test1 click<br>');
    });

    jQuery("#test1").bind("click", function test3(){
        jQuery("#result").append('test1 click<br>');
    });

    jQuery("#test2").bind("click", function test5(){
        jQuery("#result").append('test2 click<br>');
    });

    jQuery("#freez").click(function(){
        jQuery("#test1").freezeEvents();
        jQuery("#test2").freezeEvents();
    });

    jQuery("#unfreez").click(function(){
        jQuery("#test1").unFreezeEvents();
        jQuery("#test2").unFreezeEvents();
    });

});
</script>
</head>
<body>
<button id="freez">freez</button>
<button id="unfreez">un freez</button>
<br />
<div id="test1">test1 click mousemove</div>
<div id="test2">test2 click mousemove</div>
<br />
<div id="result"></div>
</body>
</html>
like image 32
andres descalzo Avatar answered Sep 25 '22 09:09

andres descalzo