Last active
June 25, 2019 12:23
-
-
Save c0depanda/47b1e9a26a80581fd9e0553db68d405c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Vue.directive('longpress', { | |
bind: function (el, binding, vNode) { | |
// Make sure expression provided is a function | |
if (typeof binding.value !== 'function') { | |
// Fetch name of component | |
const compName = vNode.context.name | |
// pass warning to console | |
let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be` | |
if (compName) { warn += `Found in component '${compName}' ` } | |
console.warn(warn) | |
} | |
// Define variable | |
let pressTimer = null | |
// Define funtion handlers | |
// Create timeout ( run function after 1s ) | |
let start = (e) => { | |
if (e.type === 'click' && e.button !== 0) { | |
return; | |
} | |
if (pressTimer === null) { | |
pressTimer = setTimeout(() => { | |
// Run function | |
handler() | |
}, 1000) | |
} | |
} | |
// Cancel Timeout | |
let cancel = (e) => { | |
// Check if timer has a value or not | |
if (pressTimer !== null) { | |
clearTimeout(pressTimer) | |
pressTimer = null | |
} | |
} | |
// Run Function | |
const handler = (e) => { | |
binding.value(e) | |
} | |
// Add Event listeners | |
el.addEventListener("mousedown", start); | |
el.addEventListener("touchstart", start); | |
// Cancel timeouts if this events happen | |
el.addEventListener("click", cancel); | |
el.addEventListener("mouseout", cancel); | |
el.addEventListener("touchend", cancel); | |
el.addEventListener("touchcancel", cancel); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handles both click and long click in same directive.
Typescript version: