Skip to content

Instantly share code, notes, and snippets.

@markmarijnissen
Created July 22, 2014 14:03
Show Gist options
  • Save markmarijnissen/b6b980f6f3503cc1ab75 to your computer and use it in GitHub Desktop.
Save markmarijnissen/b6b980f6f3503cc1ab75 to your computer and use it in GitHub Desktop.
TapEvent.js
// TapEvent
//
// Adds a "tap" event to all surfaces.
//
// Usage:
//
// require("TapEvent") // require TapEvent ONCE BEFORE calling surface.on!
// surface.on("tap", ... )
//
// When is the "tap" event fired?
//
// Touchstart/mousedown + wait 200ms + no movement
// Touchstart/mousedown + touchend/touchcancel/mouseup + within 200ms + no movement
//
//
// Mark Marijnissen, 2014, based on a fiddle found here: http://jsfiddle.net/gianlucaguarini/56Szw/
//
//
define(function(require, exports, module) {
var Surface = require('famous/core/Surface');
var getPointerEvent = function(event) {
return event.targetTouches ? event.targetTouches[0] : event;
},
setListener = function(surface, events, callback) {
var eventsArray = events.split(' '), i = eventsArray.length;
while (i--) {
surface.on(eventsArray[i], callback);
}
};
function addTapEvent(surface) {
var touching = false,
canFire = false,
currentX = 0,
currentY = 0,
startX = 0,
startY = 0,
tapEvent = null,
fireTap = function(){
if (canFire && !touching && (startX === currentX) && (startY === currentY)) {
surface.emit('tap',tapEvent);
console.log('TAP');
}
canFire = false;
};
//setting the events listeners
setListener(surface, 'touchstart mousedown', function(e) {
e.preventDefault();
var pointer = getPointerEvent(e);
startX = currentX = pointer.pageX;
startY = currentY = pointer.pageY;
touching = true;
canFire = true;
tapEvent = e;
// detecting if after 200ms the finger is still in the same position
setTimeout(fireTap, 200);
});
setListener(surface, 'touchend mouseup touchcancel', function(e) {
e.preventDefault();
touching = false;
fireTap();
});
setListener(surface, 'touchmove mousemove', function(e) {
e.preventDefault();
var pointer = getPointerEvent(e);
currentX = pointer.pageX;
currentY = pointer.pageY;
});
}
var _surfaceOn = Surface.prototype.on;
Surface.prototype.on = function on(type,fn) {
if(type == "tap" && !this.tapEnabled){
addTapEvent(this);
this.tapEnabled = true;
}
_surfaceOn.call(this,type,fn);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment