You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helpers.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Create deferred object.
  3. * @returns {{promise, resolve, reject}}
  4. */
  5. export function createDeferred () {
  6. let deferred = {};
  7. deferred.promise = new Promise(function (resolve, reject) {
  8. deferred.resolve = resolve;
  9. deferred.reject = reject;
  10. });
  11. return deferred;
  12. }
  13. /**
  14. * Reload page.
  15. */
  16. export function reload () {
  17. window.location.reload();
  18. }
  19. /**
  20. * Redirects to new URL.
  21. * @param {string} url the URL pointing to the location where the user should
  22. * be redirected to.
  23. */
  24. export function redirect (url) {
  25. window.location.replace(url);
  26. }
  27. /**
  28. * Prints the error and reports it to the global error handler.
  29. * @param e {Error} the error
  30. * @param msg {string} [optional] the message printed in addition to the error
  31. */
  32. export function reportError (e, msg = "") {
  33. console.error(msg, e);
  34. if(window.onerror)
  35. window.onerror(msg, null, null,
  36. null, e);
  37. }
  38. /**
  39. * Creates a debounced function that delays invoking func until after wait
  40. * milliseconds have elapsed since the last time the debounced
  41. * function was invoked
  42. * @param fn
  43. * @param wait
  44. * @param options
  45. * @returns {function(...[*])}
  46. */
  47. export function debounce(fn, wait = 0, options = {}) {
  48. let leading = options.leading || false;
  49. let trailing = true;
  50. let isCalled = false;
  51. if (typeof options.trailing !== 'undefined') {
  52. trailing = options.trailing;
  53. }
  54. return (...args) => {
  55. if(!isCalled) {
  56. if (leading) {
  57. fn(...args);
  58. }
  59. setTimeout(() => {
  60. isCalled = false;
  61. if (trailing) {
  62. fn(...args);
  63. }
  64. }, wait);
  65. isCalled = true;
  66. }
  67. };
  68. }