简体   繁体   中英

Re-binding JQuery events

I have a series of JQuery events, as an example, below

<script>
$("#target").click(function() {
..
});

$("#anothertarget").mouseout(function() {
...
});

$("#someselector").scroll(function() {
...
});

... other JQuery events
</script>

How do I "unbind" all these events from the document so they will all stop working and re-bind them all again later without hard coding them ?

There's a couple things you can do but either way you'd need to set conditions for the events:

You could create an event that would have a conditional that will turn the event on or off.

You could set a variable within the condition that would be either true or false, and then have that variable lead to a bind or unbind event.

if(some condition is true){
    $("#target").on("click", function() {
    });
}

//your scenario may not fit this code exactly but you would need to have conditions that bind or unbind events

var temp = true;
if(some condition is true){
    $("#target").on("click", function() {
    temp = false
    });
};
if (temp == false){
   $('#target').off("click",function(){
   })
};

//the answer below by JagsSparrow is a pretty good way too

You can create bindAll & unBindAll functions and call them dynamically whenever required.

function bindAll(){
    $("#target").click(function() {
    ..
    });

    $("#anothertarget").mouseout(function() {
    ...
    });

    $("#someselector").scroll(function() {
    ...
    });
}
function unBindAll(){
    $("#target").off('click');

    $("#anothertarget").off('mouseout');

    $("#someselector").off('scroll');
}

//To bind function call
bindAll();

//To unbind function call
unBindAll();

EDIT:

We can store object of events and bind and unbind them as below

var allEvents = {
'#target':{
 event:'click',
 func:function(){
    console.log('click')
 }
},
'#anothertarget':{
    event:'mouseout',
     func:function(){
        console.log('mouseout')
     }
},
'#someselector':{
    event:'scroll',
    func:function(){
        console.log('scroll')
    }
}
}
function bindUnbindAll(isBind){
    for(var selector in allEvents){
        // Here we can carefully filter some events to bind and unbind
        var obj = allEvents[selector];
        if(isBind)
            $(selector).on(obj.event,obj.func.bind(this));
        else
           $(selector).off(obj.event);
    }
}
//to bind function call
bindUnbindAll(true);

//To unbind function call
bindUnbindAll(false);

To unbind Off , unbind can be used to remove the event, like:

$('#target').unbind('click'); 

To bind

$('#target').bind('click', function() { /* Do stuff */ });

You can put code in functions to bind/unbind events on your objects. Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM