vue-next-directive
Version:
72 lines (71 loc) • 1.92 kB
JavaScript
function debounce(input, timeout) {
let timer;
return (event) => {
if (event.target.composing === true) {
return;
}
if (timer) {
clearTimeout(timer);
timer = void 0;
}
timer = setTimeout(() => {
input(event);
clearTimeout(timer);
timer = void 0;
}, timeout);
};
}
function isFunction(param) {
return Object.prototype.toString.call(param) === "[object Function]";
}
function compositionStart(event) {
event.target.composing = true;
}
function compositionEnd(e) {
var _a;
e.target.composing = false;
const event = new Event("input", { bubbles: true });
(_a = e.target) == null ? void 0 : _a.dispatchEvent(event);
}
let inputFunction;
function findInput(el) {
const quene = [];
quene.push(el);
while (quene.length > 0) {
const current = quene.shift();
if ((current == null ? void 0 : current.tagName) === "INPUT") {
return current;
}
if (current == null ? void 0 : current.childNodes) {
quene.push(...current.childNodes);
}
}
return null;
}
var debounceInput = {
mounted(el, binding) {
const { value, arg } = binding;
if (value && isFunction(value)) {
let timeout = 600;
if (arg && !Number.isNaN(arg)) {
timeout = Number(arg);
}
inputFunction = debounce(value, timeout);
const input = findInput(el);
el._INPUT = input;
if (input) {
input.addEventListener("input", inputFunction);
input.addEventListener("compositionstart", compositionStart);
input.addEventListener("compositionend", compositionEnd);
}
}
},
beforeUnmount(el) {
if (el._INPUT) {
el._INPUT.removeEventListener("input", inputFunction);
el._INPUT.removeEventListener("compositionstart", compositionStart);
el._INPUT.removeEventListener("compositionend", compositionEnd);
}
}
};
export { debounceInput as default };