arthurpeace arthurpeace - 4 months ago 17
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('debounced');
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

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 */ };
$('el').on("click",someFunc);

and is the same:

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

$('el').on("click",someFunc2());

and ... the same as:

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

$('el').on("click",someFunc2());

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:

//EXAMPLE NESTED FUNCTION
var funcNested=function(){ 
  console.log("It is funcNested "); 
};

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

$("#test").on("click",func());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>

Comments