Skip to content

Instantly share code, notes, and snippets.

@valeriocs
Last active January 22, 2019 19:59
Show Gist options
  • Save valeriocs/e0918a76178b52dcb17c2b65e6dfa1e5 to your computer and use it in GitHub Desktop.
Save valeriocs/e0918a76178b52dcb17c2b65e6dfa1e5 to your computer and use it in GitHub Desktop.
Diretiva para VueJS implementando métodos para ganho de desempenho através de gatilhos como debounce e throttle.
const debounce = (func) => {
let timeout;
const debounced = (...args) => {
const later = () => {
timeout = null;
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, 1000);
if (!timeout) {
func(...args);
}
};
debounced.cancel = () => {
clearTimeout(timeout);
timeout = null;
};
return debounced;
};
export default debounce;
import debounce from './debounce';
import throttle from './throttle';
/**
* Esta diretiva serve para evitar disparos desnecessarios
* @Debounce - Enquanto for disparado não chama o método,
* apenas após um segundo sem disparos que o método é chamado.
* este método também interrompe a pausa caso o usuario aperte enter, chamando
* imediatamente o método.
* Exemplo de uso: <input s-trigger="func" />
* @Throttle - Este serve para clicks, no primeiro click o método é disparado
* mas evitamos disparos seguintes durante um segundo.
* Exemplo de uso: <input s-trigger:click="func" />
*
*/
export default {
name: 's-trigger',
install(Vue) {
Vue.directive('s-trigger', {
bind(el, { value, arg }) {
const fnDebounce = debounce((target) => {
value(target.value);
});
const fnThrottle = throttle((target) => {
value(target.value);
});
const element = el;
if (arg === 'click') {
element.addEventListener(arg, ({ target }) => {
return fnThrottle(target, arg);
});
}
element.addEventListener('keyup', ({ code, target }) => {
if (code === 'Enter') {
fnDebounce.cancel();
value(target.value);
}
if (code !== 'Enter') {
fnDebounce(target);
}
});
},
});
},
};
const throttleHandler = (func) => {
let throttle = Date.now();
const throttled = (...args) => {
if ((throttle + 1000 - Date.now()) < 0) {
throttle = Date.now();
func(...args);
}
};
return throttled;
};
export default throttleHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment