decksterr
decksterr

Reputation: 143

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

Upvotes: 0

Views: 219

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20132

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.

var exampleFunc=function(){
    return 1;
};

var a = exampleFunc; //a is exampleFunc reference
a= exampleFunc(); // a is return value of exampleFunc = 1

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>

Upvotes: 2

Related Questions