Skip to content

Instantly share code, notes, and snippets.

@vinzdef
Last active October 17, 2018 14:08
Show Gist options
  • Save vinzdef/adcbdeee92ed737326520af3f2c0841b to your computer and use it in GitHub Desktop.
Save vinzdef/adcbdeee92ed737326520af3f2c0841b to your computer and use it in GitHub Desktop.
DragNormalizer
import EventEmitter from 'eventemitter3'
export default class DragNormalizer extends EventEmitter {
constructor(el) {
super()
this.el = el
this.autoBind()
this.addEventListeners()
}
destroy() {
this.removeEventListeners()
}
setPointerDown() {
this.isPointerDown = true
this.el.classList.add('is-pointer-down')
}
setPointerUp() {
this.isPointerDown = false
this.pointerX = null
this.el.classList.remove('is-pointer-down')
}
setPointerX(xCoord) {
if (this.pointerX) {
this.emitDrag(xCoord)
}
this.pointerX = xCoord
}
emitDrag(xCoord) {
this.emit('drag', {
deltaX: this.pointerX - xCoord,
clientX: xCoord
})
}
onTouchStart(e) {
this.setPointerDown()
this.setPointerX(e.touches[0].clientX)
}
onTouchMove(e) {
this.setPointerX(e.touches[0].clientX)
}
onTouchEnd() {
this.setPointerUp()
}
onMouseDown() {
this.setPointerDown()
}
onMouseMove(e) {
if (this.isPointerDown) {
this.setPointerX(e.clientX)
}
}
onMouseUp() {
this.setPointerUp()
}
addEventListeners() {
this.el.addEventListener('touchstart', this.onTouchStart)
this.el.addEventListener('touchmove', this.onTouchMove)
this.el.addEventListener('touchend', this.onTouchEnd)
this.el.addEventListener('mousedown', this.onMouseDown)
this.el.addEventListener('mousemove', this.onMouseMove)
this.el.addEventListener('mouseup', this.onMouseUp)
}
removeEventListeners() {
this.el.removeEventListener('touchstart', this.onTouchStart)
this.el.removeEventListener('touchmove', this.onTouchMove)
this.el.removeEventListener('touchend', this.onTouchEnd)
this.el.removeEventListener('mousedown', this.onMouseDown)
this.el.removeEventListener('mousemove', this.onMouseMove)
this.el.removeEventListener('mouseup', this.onMouseUp)
}
autoBind() {
this.onTouchStart = this.onTouchStart.bind(this)
this.onTouchMove = this.onTouchMove.bind(this)
this.onTouchEnd = this.onTouchEnd.bind(this)
this.onMouseDown = this.onMouseDown.bind(this)
this.onMouseMove = this.onMouseMove.bind(this)
this.onMouseUp = this.onMouseUp.bind(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment