Skip to content

Instantly share code, notes, and snippets.

@vinzdef
Last active September 14, 2015 19:13
Show Gist options
  • Save vinzdef/db867b489e80d6892b5f to your computer and use it in GitHub Desktop.
Save vinzdef/db867b489e80d6892b5f to your computer and use it in GitHub Desktop.
var $ = require('jquery')
var TouchManager = function (callbacks) {
this.touchState = {
currentY: null,
currentX: null,
startY: null,
startX: null,
lastDeltaY: null,
lastDeltaX: null,
lastDirection: null
}
this.callbacks = callbacks || {}
this.doBindings()
}
TouchManager.prototype.doBindings = function() {
$('body').on('touchstart', this.touchStart.bind(this))
$('body').on('touchmove', this.touchMove.bind(this))
$('body').on('touchend touchleave touchcancel', this.touchEnd.bind(this))
}
TouchManager.prototype.touchStart = function(e) {
this.touchState.currentY = e.originalEvent.touches[0].clientY
this.touchState.startY = e.originalEvent.touches[0].clientY
this.touchState.currentX = e.originalEvent.touches[0].clientX
this.touchState.startX = e.originalEvent.touches[0].clientX
this.touchState.lastDeltaY = this.touchState.lastDeltaX = 0
if (this.callbacks.onStart)
this.callbacks.onStart()
}
TouchManager.prototype.touchMove = function(e) {
e.preventDefault()
var eventY = e.originalEvent.touches[0].clientY,
eventX = e.originalEvent.touches[0].clientX
console.log(this.touchState)
this.touchState.lastDeltaY = eventY - this.touchState.currentY
this.touchState.lastDeltaX = eventX - this.touchState.currentX
this.touchState.currentY = eventY
this.touchState.currentX = eventX
if (this.callbacks.onMove)
this.callbacks.onMove(this.touchState)
if (Math.abs(this.touchState.lastDeltaY) > Math.abs(this.touchState.lastDeltaX)
|| (!this.callbacks.onRight && !this.callbacks.onLeft) ) {
if (this.touchState.lastDeltaY > 0) {
this.touchState.lastDirection = 'up'
if (this.callbacks.onUp)
this.callbacks.onUp(this.touchState)
}
else if (this.touchState.lastDeltaY < 0) {
this.touchState.lastDirection = 'down'
if (this.callbacks.onDown)
this.callbacks.onDown(this.touchState)
}
}
if (Math.abs(this.touchState.lastDeltaX) > Math.abs(this.touchState.lastDeltaY)
|| (!this.callbacks.onUp && !this.callbacks.onDown) ) {
if (this.touchState.lastDeltaX > 0) {
this.touchState.lastDirection = 'right'
if (this.callbacks.onRight)
this.callbacks.onRight(this.touchState)
}
else if (this.touchState.lastDeltaX < 0) {
this.touchState.lastDirection = 'left'
if (this.callbacks.onLeft)
this.callbacks.onLeft(this.touchState)
}
}
console.log(this.touchState)
}
TouchManager.prototype.touchEnd = function(e) {
if (this.callbacks.onEnd)
this.callbacks.onEnd(this.touchState)
this.touchState.currentY = null
this.lastDeltaY = null
this.lastDirection = null
}
module.exports = TouchManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment