Created
September 16, 2015 08:06
-
-
Save zhanglun/13dc9eab8e737c01ac80 to your computer and use it in GitHub Desktop.
route.js v0.1.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function() { | |
| //一个储存路径的哈希表 | |
| var routes = {}; | |
| //路径注册函数 | |
| function route(path, templateurl, controller) { | |
| routes[path] = { | |
| templateurl: templateurl, | |
| controller: controller | |
| }; | |
| } | |
| var el = null; | |
| function render() { | |
| //延迟加载视图元素 | |
| el = el || document.getElementById('view'); | |
| //目前的路径url(在哈希中去除"#") | |
| var url = location.hash.slice(1) || '/'; | |
| //通过url获取路径 | |
| var route = routes[url]; | |
| // 是否同时含有视图和controller | |
| if (el && route.controller) { | |
| //使用模板引擎渲染路径的模板 | |
| // el.innerHTML = tmpl(route.templateurl, route.controller); | |
| tmpl(route.templateurl, route.controller) | |
| .then(function(data) { | |
| el.innerHTML = data; | |
| }); | |
| } | |
| } | |
| function getTemplates(url) { | |
| return new Promise(function(resolve, reject) { | |
| var done = false; | |
| var xhr = new XMLHttpRequest(); | |
| xhr.open('GET', url, true); | |
| xhr.onreadystatechange = function() { | |
| if (xhr.readyState == 4) { | |
| if (xhr.status == 200 && !done) { | |
| done = true; | |
| resolve(xhr.responseText); | |
| } else { | |
| reject(new Error(xhr.statusText)); | |
| } | |
| } | |
| }; | |
| xhr.send(null); | |
| }); | |
| } | |
| function tmpl(templateurl, controller) { | |
| return getTemplates(templateurl) | |
| .then(function(res) { | |
| controller(res); | |
| return res; | |
| }) | |
| .then(function(res) { | |
| console.log(res); | |
| return res; | |
| }); | |
| } | |
| //监听哈希变化 | |
| window.addEventListener('hashchange', render); | |
| //监听页面载入 | |
| window.addEventListener('load', render); | |
| window.route = route; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment