touch.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var TOUCH_INPUT_MAP = {
  2. touchstart: INPUT_START,
  3. touchmove: INPUT_MOVE,
  4. touchend: INPUT_END,
  5. touchcancel: INPUT_CANCEL
  6. };
  7. var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
  8. /**
  9. * Multi-user touch events input
  10. * @constructor
  11. * @extends Input
  12. */
  13. function TouchInput() {
  14. this.evTarget = TOUCH_TARGET_EVENTS;
  15. this.targetIds = {};
  16. Input.apply(this, arguments);
  17. }
  18. inherit(TouchInput, Input, {
  19. handler: function MTEhandler(ev) {
  20. var type = TOUCH_INPUT_MAP[ev.type];
  21. var touches = getTouches.call(this, ev, type);
  22. if (!touches) {
  23. return;
  24. }
  25. this.callback(this.manager, type, {
  26. pointers: touches[0],
  27. changedPointers: touches[1],
  28. pointerType: INPUT_TYPE_TOUCH,
  29. srcEvent: ev
  30. });
  31. }
  32. });
  33. /**
  34. * @this {TouchInput}
  35. * @param {Object} ev
  36. * @param {Number} type flag
  37. * @returns {undefined|Array} [all, changed]
  38. */
  39. function getTouches(ev, type) {
  40. var allTouches = toArray(ev.touches);
  41. var targetIds = this.targetIds;
  42. // when there is only one touch, the process can be simplified
  43. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  44. targetIds[allTouches[0].identifier] = true;
  45. return [allTouches, allTouches];
  46. }
  47. var i,
  48. targetTouches,
  49. changedTouches = toArray(ev.changedTouches),
  50. changedTargetTouches = [],
  51. target = this.target;
  52. // get target touches from touches
  53. targetTouches = allTouches.filter(function(touch) {
  54. return hasParent(touch.target, target);
  55. });
  56. // collect touches
  57. if (type === INPUT_START) {
  58. i = 0;
  59. while (i < targetTouches.length) {
  60. targetIds[targetTouches[i].identifier] = true;
  61. i++;
  62. }
  63. }
  64. // filter changed touches to only contain touches that exist in the collected target ids
  65. i = 0;
  66. while (i < changedTouches.length) {
  67. if (targetIds[changedTouches[i].identifier]) {
  68. changedTargetTouches.push(changedTouches[i]);
  69. }
  70. // cleanup removed touches
  71. if (type & (INPUT_END | INPUT_CANCEL)) {
  72. delete targetIds[changedTouches[i].identifier];
  73. }
  74. i++;
  75. }
  76. if (!changedTargetTouches.length) {
  77. return;
  78. }
  79. return [
  80. // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  81. uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
  82. changedTargetTouches
  83. ];
  84. }