0

New to js-classes so this might be a rookie mistake, but here goes:

I'm trying to run a throttled event when scrolling

scrollEvent = () =>{
   console.log('test')
}

When I have a throttle like this:

throttle = (fn, wait) => {
    var time = Date.now();
    return function() {
        if ((time + wait - Date.now()) < 0 && !transitioning) {
            fn();
            time = Date.now();
        }
    }
}

window.addEventListener('scroll', throttle(scrollEvent, 50));

It works fine, but when I try to move the throttle to a class:

Throttle = class{
        constructor(){
            this.on = true; 
        }
        run(fn, wait) {
            var time = Date.now();
            return function() {
                if ((time + wait - Date.now()) < 0 && this.on) {
                    fn();
                    time = Date.now();
                }
            }
        },
scroll = new Throttle();
window.addEventListener('scroll', scroll.run(scrollEvent, 50));

The event won't trigger on scroll.

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • Why would you make that a class? There's no good reason for having an instance here. – Bergi Mar 28 '18 at 21:35
  • `this` in the function returned by `scroll.run()` is chosen by the event triggerer, it does refer to `window` not to the instance and `this.on` is always `undefined`. – Bergi Mar 28 '18 at 21:36
  • @Bergi Right now, the variable transitioning is a global varaible, I'd like to keep it in a scope somehow. Am very open to other suggestions. – Himmators Mar 28 '18 at 21:38
  • You also need to close the block. It's missing a `}`. The arrow function is also incorrect. Either add a `=` after `run` or remove the `=>` – sbolel Mar 28 '18 at 21:38
  • A duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – Estus Flask Mar 28 '18 at 21:38
  • @estus, same solution, but different quesitons imo :) Thanks though! – Himmators Mar 28 '18 at 21:39
  • 1
    @Himmators Ah, I see, so you'd then use `scroll.on = false/true` in your code? I guess a class would be ok for that. Just use arrow function syntax for the returned function and it should work. – Bergi Mar 28 '18 at 21:42
  • 1
    The question is same, as long as the problem behind it is understood correctly. `run` returns a callback. It shoud be `return () => {...` – Estus Flask Mar 28 '18 at 21:43
  • Thx, I understand the problem now, with the scope of "this", not sure what's the best way to get around it though... `window.addEventListener('scroll', scroll.run(()=>{scrollEvent()}, 50));` – Himmators Mar 28 '18 at 21:46

0 Answers0