當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Backbone.js router.execute()用法及代碼示例

當路由與其對應的回調匹配時,Backbone.js execute 方法在路由器內部被調用。

用法:

router.execute(callback, args)

參數說明:

callback:與路由匹配時執行。

args:它指定在 execute 方法中傳遞的參數。

讓我們舉個例子。

看這個例子:

<!DOCTYPE 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">
         var Route1 = Backbone.View.extend({

            template:'<b>This is route 1</b>',
               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);
               }
        });

        var AppRouter = Backbone.Router.extend({
           routes:{
              '':'homeRoute',
              'route/1':'homeRoute',
              'route/2':'aboutRoute',
           },

           homeRoute:function () {
              var route1 = new Route1();
              $("#content").html(route1.el);
           },

           aboutRoute:function () {
              var route2 = new Route2();
              $("#content").html(route2.el);
           }
       });
       var appRouter = new AppRouter();   

       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.html 文件中並在新瀏覽器中打開此文件。

BackboneJS execute Model



相關用法


注:本文由純淨天空篩選整理自 Backbone.js router.execute()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。