router.js 2.2 KB

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