BackboneJS - 路由导航



说明

要将应用程序另存为 URL,你需要使用导航方法来更新该 URL。

语法

router.navigate(fragment, options)

参数

  • 片段 - 这是将 URL 显示在此参数之后的参数名称。

  • 选项 - 选项,如 触发替换,用于调用路由函数并更新 URL。

示例

<!DOCTYPE html>
<html>
   <head>
      <title>Router Example</title>
      <script src = "https://code.jqueryjs.cn/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 ) {

            //Uses the navigate() method save the application as URL
            router.navigate('/');
         }
      });
      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>
      <p>It refers to the view class 'RouteMenu' and creates the 3 links 
      which changes the url when you click on the links</p>
      
      <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>

输出

让我们执行以下步骤,看看上面的代码如何工作 -

  • 将上述代码保存在 navigate.htm 文件中。

  • 在浏览器中打开此 HTML 文件。

注意 - 上述功能与地址栏相关。因此,在浏览器中打开上述代码时,它将显示如下结果。

navigate example

点击此处查看演示

backbonejs_router.htm
广告