目录

extend

描述 (Description)

它扩展了主干的路由器类,并创建了一个继承自Backbone.Router的新构造函数。

语法 (Syntax)

Backbone.Router.extend(properties, classProperties)

参数 (Parameters)

  • properties - 它提供路由器类的实例属性。

  • classProperties - 类属性附加到路由器的构造函数。

例子 (Example)

<!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>
      <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 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 starts listening to the routes and manages the history for bookmarkable URL's
         Backbone.history.start();
      </script>
   </head>
   <body>
      <!--It refers to the view class 'RouteMenu' and creates the 3 links which changes the url when you click on the links-->
      <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>

输出 (Output)

让我们执行以下步骤来查看上述代码的工作原理 -

  • 将以上代码保存在extend.htm文件中。

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

新页面打开

NOTE - 以上功能与地址栏有关。 因此,当您在浏览器中打开上述代码时,它将显示如下。

扩展例子

点击此处观看演示

↑回到顶部↑
WIKI教程 @2018