2011-12-22 91 views
2

我試圖用Backbone.js進行實驗,並嘗試重新配置其中一個標準T​​oDo教程。在路由器中初始化視圖

這是todo.js文件我開始用(不知道我來自哪裏得到它):

$(function(){ 

    AppView = Backbone.View.extend({ 

     el: $(".content"), 

     events: { 
      "keypress #new-todo": "createOnEnter", 
     }, 

     createOnEnter: function(e) { 
      if (e.keyCode != 13) return; 
      $("#todo-list").append("<li>"+$("#new-todo").val()+"</li>") 
      $("#new-todo").val(''); 
     } 

    }); 

    App = new AppView; 

}); 

我想看看,如果我能想出如何運行通過路由器來代替一切,所以我試過這個:

$(function(){ 

    AppView = Backbone.View.extend({ 

     el: $(".content"), 

     initialize: function(options) { 
      this.router = this.options.router; 
     }, 

     events: { 
      "keypress #new-todo": "createOnEnter", 
     }, 

     createOnEnter: function(e) { 
      if (e.keyCode != 13) return; 
      var term = $("$new-todo").val() 
      $("#todo-list").append("<li>"+term+"</li>") 
      $("#new-todo").val(''); 
      this.router.navigate("stage/"+term); 
     }, 

    }); 

    // create router 
    AppRouter = Backbone.Router.extend({ 

     initialize: function() { 
      // create view when router is initialized 
      new AppView({router : this}); 
     }, 

     routes: { 
      "stage/:stage" : "renderStage" 
     }, 

     renderStage: function(stage) { 
      alert(stage); 
     } 

    }); 


    App = new AppRouter; 

}); 

但似乎沒有任何工作。沒有任何事件從視野中消失,也沒有任何路線起火。當我在控制檯的調試,我可以訪問App它具有以下參數和方法:

_extractParameters 
_routeToRegExp 
bind 
initialize 
navigate 
route 
trigger 
unbind 
constructor 
+2

嘗試啓動歷史記錄:Backbone.history.start();在實例化路由器後 – rkw 2011-12-22 07:42:28

回答

2

的幾個問題與您的代碼:

  • var term = $("$new-todo").val()應該var term = $("#new-todo").val()
  • 您需要通過true作爲第二個參數來router.navigate()以表明您希望觸發路由。
  • 作爲RKW指出,不要忘記調用Backbone.history.start();在AppRouter的.initialize()

HERE是工作代碼。

0

我想你應該寫

this.view =新APPVIEW({路由器:此}) ;

代替

新APPVIEW({路由器:此});

因爲在您的代碼中,AppView實例將在創建後立即被垃圾收集,因爲您不需要引用它。

+0

'AppView'無法收集垃圾,因爲它被使用 - 例如,有處理程序註冊。 – kubetz 2011-12-22 10:34:38