0

I am working on a webapp where I have pages with multiple horizontally scrolling panels. I want to handle the horiziontal scroll via my own vanilla JS code. Given that I need to do this many times over I thought I would wrap that functionality in an ES6 class. My effort are along the following lines

class HoriScroll 
{
 constructor(id)
 {
  this.target = document.getElementById(id);
  this.target.addEventListener('touchstart',this.slideStart,{passive:true});
  this.target.addEventListener('touchmove',this.slideMove,{passive:true});
  this.target.dataset.startX = null;
  this.target.dataset.startTime = null;
  this.target.dataset.movePending = false;
 }

 slideStart(e)
 {
  if (1 === e.changedTouches.length) 
  {
   this.dataset.startX = e.changedTouches[0].screenX;
   this.dataset.startTime = Date.now();
  } 
 }
}

While I will be able to get things working this way what bothers me is the rather clumsy way I am recording startX, startTime etc - as attributes of the dataset of the horizontal scroll target HTML element. I ended up doing this since I cannot work out a way to access instance variable values in the class. For instance in slideStart this refers to the HTML element instance, not the HoriScroll class instance.

How, if at all, can this be done.

DroidOS
  • 8,530
  • 16
  • 99
  • 171
  • `this.slideStart` -> `() => this.slideStart()` – VLAZ Dec 01 '21 at 09:12
  • It will work as you said `this` inside the `slideStart` refers to the Html element, not the class itself. You can use an arrow function as @VLAZ suggests or you can bind `slideStart.bind(this)` to the class instance – Eldar Dec 01 '21 at 09:14
  • Correction to @VLAZ comment. Here is what you can do from my constructor `this.target.addEventListener('touchstart',(e)=>this.slideStart(e),{passive:true}` Without having access to the event parameter, `e` the actual touch event cannot be accessed although the class instance variables are now accessible! – DroidOS Dec 01 '21 at 09:26

0 Answers0