首页 > 语言 > JavaScript > 正文

用director.js实现前端路由使用实例

2024-05-06 15:01:55
字体:
来源:转载
供稿:网友

director.js是什么?

理解:前端的route框架,director.js客户端的路由注册/解析器,在不刷新的情况下,利用“#”号组织不同的URL路径,并根据不同的URL路径进行不同的方法调用。意思就是有什么样的路径就有什么样的方法。

场合:客户端浏览器和node.js的服务器应用。非常适合用来开发不需要刷新的单页面应用程序以及node.js应用。

兼容性:不依赖与任何库。例如jquery等。但它又和jquery能很好的融合在一起;

客户端的路由:

客户端的路由 (也称为哈希路由) 允许您指定一些关于使用URL应用状态的信息,当用户指定固定的URL,进行相应的页面显示。

简单例子

1. 单独使用

<!DOCTYPE html><html> <head>  <meta charset="utf-8">  <title>A Gentle Introduction</title>  <script   src="https://rawgit.com/flatiron/director/master/build/director.min.js">  </script>  <script>   var author = function () { console.log("author"); };   var books = function () { console.log("books"); };   var viewBook = function (bookId) {    console.log("viewBook: bookId is populated: " + bookId);   };   var routes = {    '/author': author,    '/books': [books, function() {     console.log("An inline route handler.");    }],    '/books/view/:bookId': viewBook   };   var router = Router(routes);   router.init();  </script> </head> <body>  <ul>   <li><a href="#/author">#/author</a></li>   <li><a href="#/books">#/books</a></li>   <li><a href="#/books/view/1">#/books/view/1</a></li>  </ul> </body></html> 

2当与jquery相结合

<!DOCTYPE html><html> <head>  <meta charset="utf-8">  <title>A Gentle Introduction 2</title>  <script   src="//www.vevb.com/uploads/allimg/190905/1RJ44203-1.jpg">  </script>  <script   src="https://rawgit.com/flatiron/director/master/build/director.min.js">  </script>  <script>  $('document').ready(function() {   //   // create some functions to be executed when   // the correct route is issued by the user.   //   var showAuthorInfo = function () { console.log("showAuthorInfo"); };   var listBooks = function () { console.log("listBooks"); };   var allroutes = function() {    var route = window.location.hash.slice(2);    var sections = $('section');    var section;    section = sections.filter('[data-route=' + route + ']');    if (section.length) {     sections.hide(250);     section.show(250);    }   };   //   // define the routing table.   //   var routes = {    '/author': showAuthorInfo,    '/books': listBooks   };   //   // instantiate the router.   //   var router = Router(routes);   //   // a global configuration setting.   //   router.configure({    on: allroutes   });   router.init();  });  </script> </head> <body>  <section data-route="author">Author Name</section>  <section data-route="books">Book1, Book2, Book3</section>  <ul>   <li><a href="#/author">#/author</a></li>   <li><a href="#/books">#/books</a></li>  </ul> </body></html>             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选