kapetan / vue-long-press-directive

Long press directive plugin for Vue.js
10 stars 4 forks source link

[feature request] support touch event #3

Open ALiangLiang opened 5 years ago

ALiangLiang commented 5 years ago

In mobile device, only work touch event.

SacDin commented 5 years ago

+1

GermanJablo commented 5 years ago

+1

dev-gian commented 5 years ago

If you want to make this work on mobile only, switch the listeners to touchstart and touchend. And if you also want the action to be executed ONLY on tap-and-hold (like native mobile contextual menus), then you can use the snippet below.

exports.install = function (Vue, options) {
  if (!options) options = {}
  if (!options.duration) options.duration = 2000

  Vue.directive('long-press', {
    bind: function (el, binding) {
      const self = this

      this._timeout = null
      this._hasMoved = false

      this._ontouchend = function (e) {
        self._hasMoved = false
        clearTimeout(self._timeout)
      }

      this._ontouchmove = function () {
        if (!self._hasMoved) {
          self._hasMoved = true
        }
      }

      this._ontouchstart = function (e) {
        const context = this

        self._timeout = setTimeout(function () {
          if (!self._hasMoved) {
            binding.value.call(context, e)
            self._hasMoved = false
          }
        }, options.duration)
      }

      el.addEventListener('touchstart', this._ontouchstart, false)
      el.addEventListener('touchmove', this._ontouchmove, false)
      document.addEventListener('touchend', this._ontouchend, false)
    },
    unbind: function (el) {
      clearTimeout(this._timeout)
      el.removeEventListener('touchstart', this._ontouchstart)
      el.removeEventListener('touchmove', this._ontouchmove)
      document.removeEventListener('touchend', this._ontouchend)
    }
  })
}
JCharante commented 4 years ago

In case anyone stumbles upon this, I forked this package with dev-gian's changes to add support for both touch and mouse.

https://github.com/JCharante/vue-long-press-directive

Thank you to kapetan and dev-gian

kapetan commented 4 years ago

@JCharante looks good