Last active
January 13, 2017 08:56
-
-
Save Mat-Moo/5cee68d2fec3d106fc36 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
/** | |
* VueJS 2 version | |
* Use v-moo-repeat="functionName" and on click this will be called repeatedly | |
*/ | |
Vue.directive('moo-repeat', { | |
/** | |
* Bind - this adds a mouse down and mouse up to the element | |
*/ | |
moo : function() { | |
}, | |
bind: function (el, binding, vnode) { | |
const INITIAL_TIMEOUT = 500; | |
var timeout = null, | |
repeatTimeout = 0, | |
repeatTimeoutSubtract = 0; | |
/** | |
* Callback function that gets faster and faster the longer it's held | |
*/ | |
var timeoutCallback = function() { | |
if (timeout) clearTimeout(timeout); | |
timeout = setTimeout(function() { | |
if (el.disabled) return; | |
doAction(); | |
if (repeatTimeout > 30) { | |
repeatTimeout -= repeatTimeoutSubtract; | |
repeatTimeoutSubtract = Math.round(repeatTimeoutSubtract / 1.5); | |
if (repeatTimeoutSubtract < 10) repeatTimeoutSubtract = 10; | |
} | |
timeoutCallback(); | |
}, repeatTimeout); | |
}; | |
var stop = function(e) { | |
clearTimeout(timeout); | |
e.preventDefault(); | |
}; | |
var doAction = function() { | |
binding.value(); | |
}; | |
var start = function(e) { | |
// initial click | |
doAction(); | |
// clear anything that might exist | |
repeatTimeout = INITIAL_TIMEOUT; | |
repeatTimeoutSubtract = 100; | |
timeoutCallback(); | |
// don't do standard behaviour | |
e.preventDefault(); | |
}; | |
el.addEventListener('mousedown', function(e) {start(e);}, false); | |
el.addEventListener('mouseout', function(e) {stop(e);}, false); | |
el.addEventListener('touchstart', function(e) {start(e);}, false); | |
el.addEventListener('mouseup', function(e) {stop(e);}, false); | |
el.addEventListener('touchend', function(e) {stop(e);}, false); | |
}, | |
/** | |
* Unbind the events as required | |
*/ | |
unbind: function (el, binding, vnode) { | |
el.removeEventListener('mousedown', ?, false); | |
el.removeEventListener('mouseout', ?, false); | |
el.removeEventListener('touchstart', ?, false); | |
el.removeEventListener('mouseup', ?, false); | |
el.removeEventListener('touchend', ?, false); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ta