router.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. OC.router_base_url = OC.webroot + '/index.php',
  2. OC.Router = {
  3. // register your ajax requests to load after the loading of the routes
  4. // has finished. otherwise you face problems with race conditions
  5. registerLoadedCallback: function(callback){
  6. this.routes_request.done(callback);
  7. },
  8. routes_request: $.ajax(OC.router_base_url + '/core/routes.json', {
  9. dataType: 'json',
  10. success: function(jsondata) {
  11. if (jsondata.status === 'success') {
  12. OC.Router.routes = jsondata.data;
  13. }
  14. }
  15. }),
  16. generate:function(name, opt_params) {
  17. if (!('routes' in this)) {
  18. if(this.routes_request.state() != 'resolved') {
  19. console.warn('To avoid race conditions, please register a callback');// wait
  20. }
  21. }
  22. if (!(name in this.routes)) {
  23. throw new Error('The route "' + name + '" does not exist.');
  24. }
  25. var route = this.routes[name];
  26. var params = opt_params || {};
  27. var unusedParams = $.extend(true, {}, params);
  28. var url = '';
  29. var optional = true;
  30. $(route.tokens).each(function(i, token) {
  31. if ('text' === token[0]) {
  32. url = token[1] + url;
  33. optional = false;
  34. return;
  35. }
  36. if ('variable' === token[0]) {
  37. if (false === optional || !(token[3] in route.defaults)
  38. || ((token[3] in params) && params[token[3]] != route.defaults[token[3]])) {
  39. var value;
  40. if (token[3] in params) {
  41. value = params[token[3]];
  42. delete unusedParams[token[3]];
  43. } else if (token[3] in route.defaults) {
  44. value = route.defaults[token[3]];
  45. } else if (optional) {
  46. return;
  47. } else {
  48. throw new Error('The route "' + name + '" requires the parameter "' + token[3] + '".');
  49. }
  50. var empty = true === value || false === value || '' === value;
  51. if (!empty || !optional) {
  52. url = token[1] + encodeURIComponent(value).replace(/%2F/g, '/') + url;
  53. }
  54. optional = false;
  55. }
  56. return;
  57. }
  58. throw new Error('The token type "' + token[0] + '" is not supported.');
  59. });
  60. if (url === '') {
  61. url = '/';
  62. }
  63. unusedParams = $.param(unusedParams);
  64. if (unusedParams.length > 0) {
  65. url += '?'+unusedParams;
  66. }
  67. return OC.router_base_url + url;
  68. }
  69. };