Backbone.js学习之Router

官方文档的解释:

Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page). Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.

简单的无节操的翻译一下

Web应用程序通常提供可链接,可收藏,可共享的URL在应用程序的重要位置。直到最近,散列片段(#page)被用来提供这些永久链接,但随着History API的到来,现在可以使用标准的URL(/页)。 Backbone.Router为客户端的页面提供路由,并将它们与操作、事件连接起来。对于这些浏览器还不支持History API,将转成成哈希片段的方式。
在页面加载后,你的应用程序创建完所有的路由器,一定要调用Backbone.history.start(),或Backbone.history.start({pushState:true}),以便初始化。

router(路由的)意思,显然是能够控制url指向哪个函数的。

在现在的单页应用中,所有的操作、内容都在一个页面上呈现,这意味着浏览器的url始终要定位到当前页面。那么一个页面中的左右的操作总不能都通过事件监听来完成,尤其是对于需要切换页面的场景以及需要分享、收藏固定链接的情况。所以,这便是路由存在的意义。

栗子:

HTML是这样子的

        <a href="#/default/">default</a>
        <a href="#/posts/120">Post 120</a>
        <a href="#/download/user/images/hey.gif">download gif</a>
        <a href="#/dashboard/graph">Load Route/Action View</a>
        <a href="#/manual">Manual</a>

然后呢,就是栗子的关键代码

var AppRouter = Backbone.Router.extend({
            routes: {
                "posts/:id" : "getPost",
                "download/*path": "downloadFile",  //对应的链接为<a href="#/download/user/images/hey.gif">download gif</a>
                ":route/:action": "loadView",      //对应的链接为<a href="#/dashboard/graph">Load Route/Action View</a>
                "manual": "manual",
                "*actions": "defaultRoute",
            },
            getPost: function(id) {
                alert(id);
            },
            defaultRoute : function(actions){
                alert(actions);
            },
            downloadFile: function( path ){ 
                alert(path); // user/images/hey.gif 
            },
            loadView: function( route, action ){ 
                alert(route + "_" + action); // dashboard_graph 
            },
            manual: function() {
                alert("call manual");
                app_router.navigate("/posts/" + 404, {trigger: true, replace: true});
            }
        });
        
        var app_router = new AppRouter;
        
        Backbone.history.start();

这个例子基本上就把Router的功能描述完整了。

另外Router相当于Controller;因为在早期的版本,是没有Router的,是在0.5版本从Controller改名过来的。

更多地还请移步官方文档。

posted @ 2015-01-19 12:39  myqianlan  阅读(454)  评论(0编辑  收藏  举报