index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // TODO - Add initial page loading and handlers
  2. (function($,History){
  3. var State = History.getState(),
  4. flag = false,
  5. exists = function(v){
  6. return typeof v != 'undefined';
  7. },
  8. api = function(data,callback){
  9. data.get = 'api';
  10. $.get(location.href,data,function(d){
  11. if(location.href.substr(location.href.lastIndexOf('/')+1) != d.state.url){
  12. History.pushState(d.state.data,d.state.title,d.state.url);
  13. }
  14. if(exists(callback)){
  15. callback(d);
  16. }
  17. },'json');
  18. },
  19. loadState = window.loadState = function(href,callback){
  20. $.get(href,{get:'state'},function(d){
  21. History.pushState(d.state.data,document.title,href);
  22. State = History.getState();
  23. if(exists(callback)){
  24. callback();
  25. }
  26. },'json');
  27. },
  28. apiState = window.apiState = function(href,callback){
  29. $.get(href,{get:'state'},function(d){
  30. History.replaceState(d.state.data,document.title,href);
  31. State = History.getState();
  32. if(exists(callback)){
  33. callback();
  34. }
  35. },'json');
  36. };
  37. $(document).ready(function(){
  38. $(window).on('statechange',function(){
  39. var Old = State;
  40. State = History.getState();
  41. if(State.data.type != Old.data.type || State.data.id != Old.data.id){
  42. console.log("State change. "+JSON.stringify(State));
  43. switch(State.data.type){
  44. case 'template':
  45. api(State.data,function(d){
  46. $('#content').html(Handlebars.compile(d.template)(d.context)).mCustomScrollbar('destroy');
  47. $('#content,.scroll').mCustomScrollbar({
  48. theme: 'dark-2',
  49. scrollInertia: 0
  50. });
  51. $('#content').find('a').each(function(){
  52. var href = this.href;
  53. if(href.indexOf(location.origin) != -1 && href.indexOf('#') != -1){
  54. href = href.substr(href.indexOf('#')+1);
  55. console.log('Setting up link to '+href);
  56. $(this).click(function(){
  57. loadState(href);
  58. return false;
  59. });
  60. }
  61. });
  62. });
  63. break;
  64. default:
  65. alert("Something went wrong!\nYour current state:\n"+JSON.stringify(State));
  66. }
  67. }
  68. });
  69. if($.isEmptyObject(State.data)){
  70. History.replaceState({
  71. type: 'template',
  72. id: 'index'
  73. },'Bugs','page-index');
  74. console.log('Forcing default state.');
  75. }else{
  76. flag = true;
  77. }
  78. apiState(location.href,function(){
  79. if(flag){
  80. State.data = {
  81. type: '',
  82. data: ''
  83. };
  84. }
  85. $(window).trigger('statechange');
  86. });
  87. });
  88. })(jQuery,History);