gesture.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { defaults } from '../util/util';
  2. import { DIRECTION_HORIZONTAL, DIRECTION_VERTICAL, Hammer } from './hammer';
  3. /**
  4. * @hidden
  5. * A gesture recognizer class.
  6. *
  7. * TODO(mlynch): Re-enable the DOM event simulation that was causing issues (or verify hammer does this already, it might);
  8. */
  9. export class Gesture {
  10. constructor(element, opts = {}) {
  11. this._callbacks = {};
  12. this.isListening = false;
  13. defaults(opts, {
  14. domEvents: true
  15. });
  16. this.element = element;
  17. // Map 'x' or 'y' string to hammerjs opts
  18. this.direction = opts.direction || 'x';
  19. opts.direction = this.direction === 'x' ?
  20. DIRECTION_HORIZONTAL :
  21. DIRECTION_VERTICAL;
  22. this._options = opts;
  23. }
  24. options(opts) {
  25. Object.assign(this._options, opts);
  26. }
  27. on(type, cb) {
  28. if (type === 'pinch' || type === 'rotate') {
  29. this._hammer.get(type).set({ enable: true });
  30. }
  31. this._hammer.on(type, cb);
  32. (this._callbacks[type] || (this._callbacks[type] = [])).push(cb);
  33. }
  34. off(type, cb) {
  35. this._hammer.off(type, this._callbacks[type] ? cb : null);
  36. }
  37. listen() {
  38. if (!this.isListening) {
  39. this._hammer = Hammer(this.element, this._options);
  40. }
  41. this.isListening = true;
  42. }
  43. unlisten() {
  44. let eventType;
  45. let i;
  46. if (this._hammer && this.isListening) {
  47. for (eventType in this._callbacks) {
  48. for (i = 0; i < this._callbacks[eventType].length; i++) {
  49. this._hammer.off(eventType, this._callbacks[eventType]);
  50. }
  51. }
  52. this._hammer.destroy();
  53. }
  54. this._callbacks = {};
  55. this._hammer = null;
  56. this.isListening = false;
  57. }
  58. destroy() {
  59. this.unlisten();
  60. this.element = this._options = null;
  61. }
  62. }
  63. //# sourceMappingURL=gesture.js.map