Hello. When an event occurs, the previous values ​​should be stored. For example:

var old_value = 0; window.onscroll = function() { var new_value = window.pageYOffset; if(new_value!=old_value) ...//какие-то действия old_value = new_value; } } 

But so old_value is in the global scope, which is good.

I read about closures and context binding , but I am not sure that this is what is needed to solve this problem.

Tell me, how is such a task properly implemented? Or is this only possible using global variables?

    1 answer 1

    Indeed, it can be stored in the parent scope, but this can be avoided by using for example an object:

     (function() { // это как раз замыкание, чтобы не делать наш конструктор глобальным function scrollHandler() { return this.handle.bind(this); // вернем хэндлер из конструтора, прибьем к нему this гвоздями. }; scrollHandler.prototype.handle = function(e) { var new_value = window.pageYOffset; if (new_value != this.old_value) { console.log(this.old_value, new_value); this.old_value = new_value; } } window.onscroll = new scrollHandler(); // этот обработчик изолирован и его состояние никуда, кроме обработчика событий не торчит. })(); 
     body { height: 1000vh; } 


    but it is possible and easier, something did not realize the evening:

     window.onscroll = function(e) { var new_value = window.pageYOffset; if (new_value != this.old_value) { console.log(this.old_value, new_value); this.old_value = new_value; } }.bind({}); // этот обработчик изолирован и его состояние никуда, кроме обработчика событий не торчит. bind меняет контекст на новый объект. 
     body { height: 1000vh; }