BackboneJS - Router Execute

描述

当路由匹配其对应的回调时使用。

语法

router.execute(callback, args)

参数

  • callback − 当与路由匹配时执行。

  • args − 在 execute 方法中传递的参数。

示例

<!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' 是视图类的名称
         var Route1 = Backbone.View.extend ({

            //创建路由 1 链接,用于触发后改变文本
            //点击事件
            template: '<b>This is route 1</b>',

            //'initialize' 函数为路由器实例创建新的构造函数
            initialize: function () {
               this.execute();
            },

            //当路由匹配到对应的回调函数时调用
            execute: function () {
               this.$el.html(this.template);
            }
         });
         var Route2 = Backbone.View.extend ({
            template: '<b>This is route 2</b>',
            initialize: function () {
               this.execute();
            },
            execute: function () {
               this.$el.html(this.template);
            }
         });

         //'AppRouter' 是路由器类的名称
         var AppRouter = Backbone.Router.extend ({
            routes: {
               '': 'homeRoute',
               'route/1': 'homeRoute',
               'route/2': 'aboutRoute',
            },

            //当点击路线1时,会导航到自定义视图类"Route 1"
            homeRoute: function () {
               var route1 = new Route1();
               $("#content").html(route1.el);
            },

            //当点击路线2时,会导航到自定义视图类'Route 2'
            aboutRoute: function () {
               var route2 = new Route2();
               $("#content").html(route2.el);
            }
         });
         var appRouter = new AppRouter();   //它是路由器的一个实例

         //它开始监听路线并管理可收藏 URL 的历史记录
         Backbone.history.start();
      </script>
      
   <body>
      <div id = "navigation">
         <a href = "#/route/1">route1</a>
         <a href = "#/route/2">route2</a>
      </div>
   
      <div id = "content></div>
   </body>
</html>

输出

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

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

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

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

execute example

点击此处查看演示

backbonejs_router.html