Skip to content

Instantly share code, notes, and snippets.

@rixth
Created March 26, 2015 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rixth/9ad6b3b18bcdd77797a7 to your computer and use it in GitHub Desktop.
Save rixth/9ad6b3b18bcdd77797a7 to your computer and use it in GitHub Desktop.
const LONG_PRESS_MS = 400,
LONG_PRESS_TOLERANCE = 20,
NUDGE_MS = 400,
NUDGE_THRESHOLD = 20,
SWIPE_THRESHOLD = 70;
function Touchable() {
this.after('initialize', function () {
let touches = [],
longPressTimer,
nudgeTimer,
longPressing,
swipedDistance,
nudged;
let touchDistance = (axis = 'x', frm = 0, end = (touches.length - 1)) => touches[frm][axis] - touches[end][axis];
this.on('touchstart', ({originalEvent: { touches: eventTouches }}) => {
longPressing = false;
swipedDistance = 0;
nudged = false;
touches.length = 0;
touches.push({
x: eventTouches[0].pageX,
y: eventTouches[0].pageY,
at: Date.now()
});
clearTimeout(longPressTimer);
longPressTimer = setTimeout(() => {
let distance = touchDistance();
if (distance > (LONG_PRESS_TOLERANCE * -1) && distance < LONG_PRESS_TOLERANCE) {
longPressing = true;
this.trigger('uiLongPressDown');
}
}, LONG_PRESS_MS);
});
this.on('touchmove', ({originalEvent: { touches: eventTouches }}) => {
touches.push({
x: eventTouches[0].pageX,
y: eventTouches[0].pageY,
at: Date.now()
});
let distance = touchDistance(),
absDistance = Math.abs(distance);
if (absDistance > SWIPE_THRESHOLD && swipedDistance < absDistance) {
swipedDistance = absDistance;
this.trigger('uiSwipe', {
distance: absDistance,
direction: distance > 0 ? 'LEFT' : 'RIGHT'
});
}
clearTimeout(nudgeTimer);
nudgeTimer = setTimeout(() => {
let distance = touchDistance(),
absDistance = Math.abs(distance);
if (distance > NUDGE_THRESHOLD && distance < SWIPE_THRESHOLD && !nudged) {
nudged = true;
this.trigger('uiNudge', {
distance: absDistance,
direction: distance > 0 ? 'LEFT' : 'RIGHT'
});
}
}, NUDGE_MS);
});
this.on('touchend', (event) => {
clearTimeout(nudgeTimer);
clearTimeout(longPressTimer);
if (longPressing) {
this.trigger('uiLongPressUp');
}
});
});
}
export default Touchable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment