debounce.ts 967 B

1234567891011121314151617181920212223242526272829303132333435
  1. import debounce from "lodash/debounce";
  2. import {VNode, VNodeDirective} from "vue";
  3. // Attach directive to element and wait for input to stop. Default timeout 800ms or 0.8s.
  4. export default function (el: HTMLElement, binding: VNodeDirective, vnode: VNode) {
  5. const evt = binding.arg || "input"
  6. const fire = debounce(function (e) {
  7. if (vnode.componentInstance) {
  8. vnode.componentInstance.$emit(evt+":debounced", e)
  9. } else {
  10. el.dispatchEvent(createNewEvent(evt +':debounced'))
  11. }
  12. }, parseInt(binding.value) || 800)
  13. if (binding.value !== binding.oldValue) {
  14. if (vnode.componentInstance) {
  15. vnode.componentInstance.$on(evt, fire)
  16. } else {
  17. (el as any)["on"+evt] = fire
  18. }
  19. }
  20. }
  21. // IE Support
  22. function createNewEvent(eventName: string) {
  23. var e: Event
  24. if (typeof(Event) === 'function') {
  25. e = new Event(eventName, {bubbles: true, cancelable: true})
  26. } else {
  27. e = document.createEvent('Event')
  28. e.initEvent(eventName, true, true)
  29. }
  30. return e
  31. }