helpers.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * Various helper functions
  3. */
  4. /**
  5. * A PHP-style substr_replace
  6. *
  7. * Supports negative start and length and omitting length, but not
  8. * str and replace arrays.
  9. * See http://php.net/substr-replace for further documentation.
  10. */
  11. function substr_replace(str, replace, start, length) {
  12. var a2, b1;
  13. a2 = (start < 0 ? str.length : 0) + start;
  14. if (typeof length === 'undefined') {
  15. length = str.length - a2;
  16. } else if (length < 0 && start < 0 && length <= start) {
  17. length = 0;
  18. }
  19. b1 = (length < 0 ? str.length : a2) + length;
  20. return str.substring(0, a2) + replace + str.substring(b1);
  21. }
  22. /**
  23. * Bind variables to a function call creating a closure
  24. *
  25. * Use this to circumvent variable scope problems when creating closures
  26. * inside a loop
  27. *
  28. * @author Adrian Lang <lang@cosmocode.de>
  29. * @link http://www.cosmocode.de/en/blog/gohr/2009-10/15-javascript-fixing-the-closure-scope-in-loops
  30. * @param functionref fnc - the function to be called
  31. * @param mixed - any arguments to be passed to the function
  32. * @returns functionref
  33. */
  34. function bind(fnc/*, ... */) {
  35. var Aps = Array.prototype.slice,
  36. // Store passed arguments in this scope.
  37. // Since arguments is no Array nor has an own slice method,
  38. // we have to apply the slice method from the Array.prototype
  39. static_args = Aps.call(arguments, 1);
  40. // Return a function evaluating the passed function with the
  41. // given args and optional arguments passed on invocation.
  42. return function (/* ... */) {
  43. // Same here, but we use Array.prototype.slice solely for
  44. // converting arguments to an Array.
  45. return fnc.apply(this,
  46. static_args.concat(Aps.call(arguments, 0)));
  47. };
  48. }
  49. /**
  50. * Report an error from a JS file to the console
  51. *
  52. * @param e The error object
  53. * @param file The file in which the error occurred
  54. */
  55. function logError(e, file) {
  56. if (window.console && console.error) {
  57. console.error('The error "%s: %s" occurred in file "%s". ' +
  58. 'If this is in a plugin try updating or disabling the plugin, ' +
  59. 'if this is in a template try updating the template or switching to the "dokuwiki" template.',
  60. e.name, e.message, file);
  61. if(e.stack) {
  62. console.error(e.stack);
  63. }
  64. }
  65. }