- BackboneJS 教程
- BackboneJS - 主頁
- BackboneJS - 概覽
- BackboneJS - 環境設定
- BackboneJS - 應用程式
- BackboneJS - 事件
- BackboneJS - 模型
- BackboneJS - 集合
- BackboneJS - 路由
- BackboneJS - 歷史記錄
- BackboneJS - 同步
- BackboneJS - 檢視
- BackboneJS - 實用工具
- BackboneJS 有用資源
- BackboneJS - 快速指南
- BackboneJS - 資源
- BackboneJS - 討論
BackboneJS - 路由路由
說明
為路由提供一個路由並使用 斜槓 後跟 冒號 和引數名來附加路由的引數。
語法
router.route(route, name, [callback])
引數
route − 可能是一個路由字串或一個正則表示式。
name − 這是路由引數的名稱。
callback − 這是路由的名稱,如果省略了 callback 引數。
示例
<!DOCTYPE html>
<html>
<head>
<title>Router Example</title>
<script src = "https://code.jquery.com/jquery-2.1.3.min.js"
type = "text/javascript"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
type = "text/javascript"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
type = "text/javascript"></script>
</head>
<script type = "text/javascript">
//'RouteMenu' is a name of the view class
var RouteMenu = Backbone.View.extend ({
el: '#routemenu', //'el' defines which element to be used as the view reference
//defines a click event to be occur on link
events: {
'click a' : 'onClick'
},
//After clicking on a link, router calls 'navigate' to update URL
onClick: function( e ) {
router.navigate('/');
}
});
//'Router' is a name of the router class
var Router = Backbone.Router.extend ({
//The 'routes' maps URLs with parameters to functions on your router
routes: {
'route/:id' : 'defaultRoute'
},
});
//'routemenu' is an instance of the view class
var routemenu = new RouteMenu();
//It start listening to the routes and manages the history for bookmarkable URL's
Backbone.history.start();
</script>
<body>
<section id = "routemenu">
<ul>
<li> <a href = "#/route/1">route 1 </a> </li>
<li> <a href = "#/route/2">route 2 </a> </li>
<li> <a href = "#/route/3">route 3 </a> </li>
</ul>
</section>
</body>
</html>
輸出
讓我們執行以下步驟來了解上述程式碼的工作原理 −
將上述程式碼儲存在 route.htm 檔案中。
在瀏覽器中開啟此 HTML 檔案。
注意 − 上述功能與位址列相關。因此,當您在瀏覽器中開啟上述程式碼時,它將顯示如下結果。
backbonejs_router.htm
廣告