debouncedWatch.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
  2. import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
  3. var _excluded = ["eventFilter"],
  4. _excluded2 = ["debounce"];
  5. // copy from https://github.dev/vueuse/vueuse
  6. import { unref, watch } from 'vue';
  7. var bypassFilter = function bypassFilter(invoke) {
  8. return invoke();
  9. };
  10. /**
  11. * Create an EventFilter that debounce the events
  12. *
  13. * @param ms
  14. */
  15. export function debounceFilter(ms) {
  16. var timer;
  17. var filter = function filter(invoke) {
  18. var duration = unref(ms);
  19. if (timer) clearTimeout(timer);
  20. if (duration <= 0) return invoke();
  21. timer = setTimeout(invoke, duration);
  22. };
  23. return filter;
  24. }
  25. /**
  26. * @internal
  27. */
  28. function createFilterWrapper(filter, fn) {
  29. function wrapper() {
  30. var _this = this;
  31. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  32. args[_key] = arguments[_key];
  33. }
  34. filter(function () {
  35. return fn.apply(_this, args);
  36. }, {
  37. fn: fn,
  38. thisArg: this,
  39. args: args
  40. });
  41. }
  42. return wrapper;
  43. }
  44. // implementation
  45. export function watchWithFilter(source, cb) {
  46. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  47. var _options$eventFilter = options.eventFilter,
  48. eventFilter = _options$eventFilter === void 0 ? bypassFilter : _options$eventFilter,
  49. watchOptions = _objectWithoutProperties(options, _excluded);
  50. return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
  51. }
  52. // implementation
  53. export default function debouncedWatch(source, cb) {
  54. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  55. var _options$debounce = options.debounce,
  56. debounce = _options$debounce === void 0 ? 0 : _options$debounce,
  57. watchOptions = _objectWithoutProperties(options, _excluded2);
  58. return watchWithFilter(source, cb, _objectSpread(_objectSpread({}, watchOptions), {}, {
  59. eventFilter: debounceFilter(debounce)
  60. }));
  61. }