router.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //构造函数
  2. function Router() {
  3. this.routes = {};
  4. this.currentUrl = '';
  5. }
  6. Router.prototype.route = function(path, callback) {
  7. this.routes[path] = callback || function(){};//给不同的hash设置不同的回调函数
  8. };
  9. Router.prototype.refresh = function() {
  10. console.log(location.search.slice(1));//获取到相应的hash值
  11. this.currentUrl = location.search.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
  12. // console.log(this.currentUrl);
  13. let params = new URLSearchParams(document.location.search);
  14. let view = params.get("view");
  15. if(this.currentUrl&&this.currentUrl!='/'){
  16. this.routes[view]();//根据当前的hash值来调用相对应的回调函数
  17. }
  18. };
  19. Router.prototype.init = function() {
  20. window.addEventListener('load', this.refresh.bind(this), false);
  21. //window.addEventListener('hashchange', this.refresh.bind(this), false);
  22. window.onpopstate = function(event) {
  23. console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
  24. _view = event.state.view;
  25. _tags = event.state.tag;
  26. _channel = event.state.channel;
  27. list_tag = _tags.split(',');
  28. switch (_view) {
  29. case "community":
  30. community_onload();
  31. break;
  32. case "category":
  33. palicanon_onload();
  34. palicanonGetChapter();
  35. break;
  36. default:
  37. break;
  38. }
  39. };
  40. }
  41. //给window对象挂载属性
  42. window.Router = new Router();
  43. window.Router.init();