Backbone Router

动态路由

大部分非常灵活的框架允许你定义静态、动态的路由,可带参数。举个例子你希望得到一个带id的url的请求。 

这是你的url    http://example.com/#/posts/12

当这个url 触发时你想到得到url字符串里的id    ,以下是实现代码

<script>
var AppRouter = Backbone.Router.extend({
routes: {
"/posts/:id": "getPost",
"*actions": "defaultRoute" // Backbone will try match the route above first
},
getPost: function( id ) {
// Note the variable in the route definition being passed in here
alert( "Get post number " + id );
},
defaultRoute: function( actions ){
alert( actions );
}
});
// Instantiate the router
var app_router = new AppRouter;
// Start Backbone history a neccesary step for bookmarkable URL's
Backbone.history.start();

</script>

 

routes: {

  "/posts/:id":"getPost",    //<a href="http://example.com/#/posts/121">Example</a>

  "/download/*path": "downloadFile", //<a href="http://example.com/#/download/user/imges/hey.gif">Example</a>      *能匹配多个链接 

  "/:route/:action": "loadView",    // //<a href="http://example.com/#/dashboard/graph">Example</a>     //route  action 

},



getPost: function( id ) {

    alert(id);

},



downloadFile: function(path){

    alert(path);

},

loadView:function(route,action) {

  alert(route,action);

}

 

: 会将匹配到变量传递到处理的函数

Routes非常的强大,理想情况下不应该有太多。你应该使用锚点来做SEO,用google 查一下   “google seo hashbangs”记得为出现的错误请求。

你可能感兴趣的:(backbone)