debouncedWatch.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. // copy from https://github.dev/vueuse/vueuse
  3. var __rest = this && this.__rest || function (s, e) {
  4. var t = {};
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  6. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  7. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  8. }
  9. return t;
  10. };
  11. import { unref, watch } from 'vue';
  12. const bypassFilter = invoke => {
  13. return invoke();
  14. };
  15. /**
  16. * Create an EventFilter that debounce the events
  17. *
  18. * @param ms
  19. */
  20. export function debounceFilter(ms) {
  21. let timer;
  22. const filter = invoke => {
  23. const duration = unref(ms);
  24. if (timer) clearTimeout(timer);
  25. if (duration <= 0) return invoke();
  26. timer = setTimeout(invoke, duration);
  27. };
  28. return filter;
  29. }
  30. /**
  31. * @internal
  32. */
  33. function createFilterWrapper(filter, fn) {
  34. function wrapper() {
  35. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36. args[_key] = arguments[_key];
  37. }
  38. filter(() => fn.apply(this, args), {
  39. fn,
  40. thisArg: this,
  41. args
  42. });
  43. }
  44. return wrapper;
  45. }
  46. // implementation
  47. export function watchWithFilter(source, cb) {
  48. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  49. const {
  50. eventFilter = bypassFilter
  51. } = options,
  52. watchOptions = __rest(options, ["eventFilter"]);
  53. return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
  54. }
  55. // implementation
  56. export default function debouncedWatch(source, cb) {
  57. let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  58. const {
  59. debounce = 0
  60. } = options,
  61. watchOptions = __rest(options, ["debounce"]);
  62. return watchWithFilter(source, cb, _extends(_extends({}, watchOptions), {
  63. eventFilter: debounceFilter(debounce)
  64. }));
  65. }