router.js

/**
 * 简易路由
 */
var Router = {

    // 路由初始
    init: function () {
        this.routes = {};
        this.useRouter();
    },

    // 路由配置
    route: function (path, cb) {
        this.routes[path] = cb || function () {};
    },

    // 路由机制
    refresh: function () {
        try {
            this.routes[location.hash.slice(1) || '/'](location.hash.slice(2));
        }
        catch (ex) {
            throw new Error('route未配置 => \"' + (location.hash.slice(1) || '空URL') + '\"');
        }
    },

    // 路由监听
    useRouter: function () {
        window.addEventListener('load', this.refresh.bind(this), false);
        window.addEventListener('hashchange', this.refresh.bind(this), false);
    }
};

Router.init();

 

posted @ 2016-06-23 16:07  koala_熊  Views(322)  Comments(0Edit  收藏  举报