2012-04-11 92 views
1

我有一個Rails 3.2.3應用與Backbone.js和我在我的Backbone.history上使用pushState。Backbone.js路由沒有被觸發

的問題

當我點擊它去說「/富」,以顯示與ID任命一個鏈接:1,然後骨幹路由器到達,首先,我可以前滑軌路由器快速查看接管並抱怨沒有/ foo路線。

我Backbone.js的代碼

這是我的骨幹路由器。

window.AppointmentApp = new (Backbone.Router.extend({ 
    routes: { 
     "": "index", 
     "foo": "foo", 
     "appointments": "index", 
     "appointments/:id": "show" 
    }, 
    foo: function(){ 
     $("#app").append("foo<br />"); 
    }, 
    initialize: function() { 
     this.appointments = new Appointments(); 
     this.appointmentListView = new AppointmentListView({ collection: this.appointments }); 
     this.appointmentListView.render(); 
    }, 
    start: function() { 
     Backbone.history.start({pushState: true}); 
    }, 
    index: function() { 
     $("#app").html(this.appointmentListView.el); 
     this.appointments.fetch(); 
    }, 
    show: function(id) { 
     console.log("Enter show"); 
    } 
})); 

它應該停留在同一頁面上並在#app div附加一個'foo',但它永遠不會。

骨幹指數觀衆

window.AppointmentListView = Backbone.View.extend({ 
    template: JST["appointments/index"], 
    events: { 
     "click .foo": function(){Backbone.history.navigate("foo");}, 
    }, 
    comparator: function(appointment){ 
     return appointment.get('topic'); 
    }, 
    initialize: function(){ 
     this.collection.on('reset', this.addAll, this); 
    }, 
    render: function(){ 
     this.$el.html(this.template); 
     this.addAll(); 
     return this; 
    }, 
    addAll: function() { 
     this.collection.forEach(this.addOne, this); 
    }, 
    addOne: function(appointment){ 
     var appointmentView = new AppointmentView({model: appointment}); 
     this.$el.append(appointmentView.render().el); 
    } 
}); 

應用程序/資產/模板/約會/ Index.jst.ejs

<h1>Appointments</h1> 
<a href="/foo" class="foo">Say Foo</a> 
<a href=appointments/add>Add</a> 
<div id="app"></div> 

我用pushState的,因爲它讓我保持歷史和後退按鈕功能。

Backbone.history.navigate不會調用我的Backbone路由,而是調用Rails路由。我該如何解決這個問題?

我應該試圖設置Backbone來接受諸如'約會/ 1'之類的路線並採取控制措施,還是必須使用像上面那樣的Backbone.history.navigate調用來使用單擊事件?

回答

0

您需要從您的click .foo事件處理程序返回false,否則瀏覽器將繼續,就像您正常點擊鏈接並請求服務器上的實際/foo頁面一樣。

我認爲你也打電話給Backbone.history.navigate("foo");錯誤 - Backbone.history沒有navigate功能,據我可以從文檔中看到。您實際上應該正在呼叫您的Backbone.Router實例,然後傳遞trigger選項以使其呼叫觸發路由。例如:

window.AppointmentApp.navigate("foo", { trigger : true }); 

你可能已經知道這一點,但如果你使用pushState的計劃,那麼你真的應該更新您的服務器端支持所有的客戶端做的URL。否則,如果用戶決定複製&將該URL粘貼到另一個選項卡中,則它們將會碰到抱怨沒有路由的rails。

+0

我認爲pushState背後的想法是你不必使用URL片段? – map7 2012-04-11 23:50:57

+0

如果我刪除pushState並將您的導航行更改爲「#/ foo」,那麼它一切正常,但URL片段不是真正的URL。我正在尋找一種方法來實現pushState – map7 2012-04-12 00:03:17

+0

@ map7啊,對不起,我不太明白你在問什麼。我已經更新了我的答案 – obmarg 2012-04-12 09:25:51