arthurpeace arthurpeace - 1 year ago 70
jQuery Question

jQuery event object acessible from within anonymous function inside event handler?

I've been running into some performance issues when a scroll event gets fired on a project i'm working on and found that debouncing the taxing stuff would be a viable solution:

jQuery(document).ready(function() {
jQuery(window).on('scroll', debounce(function(e) {
console.log(e); // will print the corresponding jQuery object
// some heavy work
}, 250, true);

function debounce(func, wait, immediate) {
var timeout;
return function() {
var obj = this, args = arguments;
if (timeout) clearTimeout(timeout);
else if (immediate) func.apply(obj, args);
timeout = setTimeout(function() {
if (!immediate) func.apply(obj, args);
timeout = null;
}, wait || 100);

My question is, how come the jQuery event object is properly handed over within debounce() ?
Isn't it supposed to be passed as first argument of function set as handler, here being debounce() ?

This solution seems to get the job done just fine, but is there some conceptual thing i'm missing here ?

NB: credits to John Hann for the debouncing function

Answer Source

Answer is that jquery event gets return of debounce function, in return it has anonymous function so it exacly what event want to get in parameters.

Some examples the same behavior:

$('el').on("click",function(e){ /* do something */ })

is the same as

someFunc=function(){ /* do something */ };

and is the same:

someFunc=function(){ /* do something */ };
someFunc2=function(){ /* do something 2 */ return someFunc;  };


and ... the same as:

  /* do something 2 */ 
  return function(){ /* do something */ }  


Conclusion - using function in next function is using its return value.

var a=5;
var getA(){ return 5; };

var twentyfive=a*getA(); //25

Some example of using function return as another function:

var funcNested=function(){ 
  console.log("It is funcNested "); 

var func=function(){ return funcNested; };

<script src=""></script>
<button id="test">Click me</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download