简体   繁体   中英

Is there a way I can pass event object as well as other arguments to debounced event handler?

I am developing a custom scrollbar, and for performance reasons I want to add debounce to a mousemove event. The problem is the event object doesn't get passed to the handler and I get undefined .

here is what i wanna do:

function myFunc (a, b, event) {some code}
element.on('mousemove' , debounce(myfunc));

doesn't work! I also tried:

let myDBFunc = debounce(myFunc, 200)
element.on('mousemove', function(event){
    myDBFunc(a, b, event);
});

nothing! any ideas?

UPDATE: the debounce function:

function debounce(func, wait = 20,immediate = true){
    let timeout;
    return function() {
        let context = this, args = arguments;
        let later = function () {
            timeout = null;
            if(!immediate) func.apply(context, args);
        };
        let callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context.args) ; //edited to func.apply(context, args);
    };
}

It does not work because the a , b arguments are not passed, and the event object gets passed as first argument. You could pass all three of them via an anonymous function, like this:

element.on('mousemove' , (e) => debounce(myfunc)(a, b, e));

Also, after you provided the debounce function, it turns out there is an error in that function near the end. Change:

func.apply(context.args)

to:

func.apply(context, args)

Furthermore, that debounce function will call nothing when you use the default arguments, or even when you provide a nonzero wait argument and true for immediate . It will work better when you change:

if(!immediate) func.apply(context, args);

to:

if(!callNow) func.apply(context, args);

Demo

For your purpose I would use this debounce function. See demo below with the extra arguments:

 function debounce(func, wait = 200) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => { timeout = setTimeout(() => timeout = null, wait); func.apply(this, args); }, timeout ? wait : 0); }; } const element = $('div'); function myfunc(a, b, e) { console.log(a, b, e.target.tagName, performance.now()); } const f = debounce(myfunc); let a = 1, b = 2; element.on('mousemove' , (e) => f(a, b, e)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div>move mouse here</div> 

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