当前位置 : 主页 > 网络编程 > JavaScript >

简单的小路由

来源:互联网 收集:自由互联 发布时间:2021-06-28
h5小页面 (function (win, doc) { "use strict"; function Router(option) { this.routes = option.routes; this.viewHandle = option.viewHandle; this.currentUrl = ''; this.v = {}; this._init(); } Router.prototype._binEvent = function () { win.a
h5小页面
(function (win, doc) {
  "use strict";

  function Router(option) {
    this.routes = option.routes;
    this.viewHandle = option.viewHandle;
    this.currentUrl = '';

    this.v = {};
    this._init();
  }

  Router.prototype._binEvent = function () {
    win.addEventListener('DOMContentLoaded', this.refresh.bind(this), false);
    win.addEventListener('hashchange', this.refresh.bind(this), false);
  };

  Router.prototype.refresh = function () {
    var hash = win.location.hash;
    if (!hash) {
      win.location.hash = '/';
      return;
    }

    this.currentUrl = hash.match(/#([\/\w]*)/)[1];
    var mothod = this.routes[this.currentUrl];

    if (mothod) {
      this.viewHandle(mothod);
    }
  };

  Router.prototype._init = function () {
    this._binEvent();
  };

  Router.prototype.go = function (path, data) {
    win.location.hash = path;
    this.v.data = data;
  }

  win.Router = Router;

})(window, document);
上一篇:jquery_ajax.js
下一篇:Crop Image
网友评论