2012-03-30 45 views
1

在Backbone.js的文檔,在the entry for the Router.routes method,據稱在Backbone.js中,如何「聽路由器」(響應視圖/模型中的路由器事件)?

當訪問者按下後退按鈕,或者輸入一個URL,和特定的路線一致, 動作的名稱將被解僱作爲事件,以便其他對象可以收聽路由器 並得到通知。

我試圖在這個相對簡單的例子來實現這一點:

相關JS:

$(document).ready(function(){ 
    // Thing model 
    window.Thing = Backbone.Model.extend({ 
     defaults: { 
      text: 'THIS IS A THING' 
     } 
    }); 

    // An individual Thing's View 
    window.ThingView = Backbone.View.extend({ 
     el: '#thing', 

     initialize: function() { 
      this.on('route:showThing', this.anything); 
     }, 

     anything: function() { 
      console.log("THIS DOESN'T WORK! WHY?"); 
     }, 

     render: function() { 
      $(this.el).html(_.template($('#thing-template').html(), { 
       text: this.model.get('text') 
      })); 
      return this; 
     } 
    }); 

    // The Router for our App 
    window.ThingRouter = Backbone.Router.extend({ 
     routes: { 
      "thing":  "showThing" 
     }, 

     showThing: function() { 
      console.log('THIS WORKS!'); 
     } 
    }); 

    // Modified from the code here (from Tim Branyen's boilerplate) 
    // http://stackoverflow.com/questions/9328513/backbone-js-and-pushstate                
    window.initializeRouter = function (router, root) { 
     Backbone.history.start({ pushState: true, root: root }); 
     $(document).on('click', 'a:not([data-bypass])', function (evt) { 

      var href = $(this).attr('href'); 
      var protocol = this.protocol + '//'; 

      if (href.slice(protocol.length) !== protocol) { 
       evt.preventDefault(); 
       router.navigate(href, true); 
      } 
     }); 
     return router; 
    } 

    var myThingView = new ThingView({ model: new Thing() }); 
    myThingView.render(); 
    var myRouter = window.initializeRouter(new ThingRouter(), '/my/path/'); 
}); 

相關的HTML:

<div id="thing"></div> 

    <!-- Thing Template --> 
    <script type="text/template" id="thing-template"> 
    <a class='task' href="thing"><%= text %></a> 
    </script> 

然而,路由器事件中引用在視圖的初始化函數中似乎沒有被拾取(其他一切正常 - 我正在成功調用「showThi」 ng「方法在路由器中定義)。

我相信我必須對本聲明所指的文檔有一些誤解。因此,我在尋找的答案是:我希望有人修改我的代碼,以便它可以通過路由器事件獲得視圖,或者清楚地解釋我列出的路由器文檔上面打算我們做,理想情況下與替代代碼示例(或使用我的,修改)。

非常感謝您提供的任何幫助!

+0

你不應該在initialize方法中使用'router.on('route:thing',this.anything)'' – WarFox 2014-03-03 07:27:34

回答

2

這很可能是因爲您將偵聽器綁定到了錯誤的對象。在你的View中試試這個:

window.ThingView = Backbone.View.extend({ 

    initialize: function() { 
      myRouter.on('route:showThing', this.anything); 
    }, 

... 
+2

好的,明白了。我想我誤解了這部分內容:「...以便其他對象可以聽路由器,」不知何故將它讀爲「...其他對象可以聽路由器*事件*」。我想這意味着,從架構的角度來說,最好實例化一個全局的路由器,即視圖能夠根據需要進行引用。謝謝drinchev! – 2012-04-02 01:38:41

相關問題