简体   繁体   中英

How to unbind event handler and pass arguments simultaneously?

I have a following scenario in my code:

 function outer() { console.log(x); //after some time if certain conditions are met remove handler from #red $("#red").off("click", outer); } function inner() { var x = 786; $("#red").click(outer); } inner(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="red"> RED </div> 

The outer function cannot be declared inside inner function. The example is a simplified version of my actual problem. In my actual problem inner function is an each which executes on success of ajax request. For the code to work I have to pass x to outer as an argument because x is out of scope of outer . Then the code would be like:

 function outer(x) { console.log(x); } function inner() { var x = 786; $("#red").click(function(){ outer(x); }); } inner(); //after some time if certain conditions are met remove handler from #red $("#red").off("click", outer); // Dosen't work now 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="red"> RED </div> 

In the first example I could unbind the click handeler but could not pass x as argument. In second example I can pass x as argument but cannot unbind the event.

  • How do I unbind event handler and pass arguments simultaneously? Please also note, I don't want to remove all handlers with $("#red").off("click") .

I tried using closures but they didn't work too:

 function extra(x) { function outer(x) { console.log(x); //after some time if certain conditions are met remove handler from #red $("#red").off("click", extra(x)); // Hangs the computer } return outer; } function inner() { var x = 786; $("#red").click(extra(x)); } inner(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="red"> RED </div> 

Clicking on RED hangs my computer so I could not test this.

Thanks...

.off() works with .on() . So your code could look like this:

function outer(x) {
  $('body').append('<br>button clicked and event removed! x value: ' + x);
  $("#red").off(".onlythis");
}

function inner() {
  var x = 786;  
  $("#red").on('click.onlythis', function(){ outer(x); }); 
}

inner();

jsfiddle example

jQuery .off()

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