2012-11-17 25 views
2

我一直在爲此奮鬥了很長一段時間。我使用Backbone.js和Require.js。我試圖告訴Backbone根據當前URL(不是哈希)顯示特定的視圖。我的代碼如下所示:在Backbone.js中獲取URL碎片而不是散列碼

define(['jquery','underscore','backbone', 'views/manage_pages'], function($, _, Backbone, ManagePages) { 
    var AppRouter = Backbone.Router.extend({ 
    routes:{ 
     '/new_page': "showPageForm", 
     '/edit_page': "showPageEditForm", 
     '*actions': "showPageForm" 
    }, 
    }); 
    var initialize = function(){ 
    appRouter = new AppRouter; 
    appRouter.on("route:showPageForm", function(){ 
     console.log('hej'); 
    }); 
    appRouter.on("route:showPageEditForm", function(){ 
     console.log('ho'); 
    }); 
    var page_form = new ManagePages(); 
     Backbone.history.start(); 
    } 
    return { 
     initialize: initialize 
    } 
    }); 

所以基本上,當用戶進入http://example.com/new_page應該記錄<code>hej</code>,當他去http://example.com/editpage應該登錄<code>ho</code>。我不知道如何做到這一點,即使有可能。誰能幫我?

回答

8

您可以使用Backbone對HTML5 push-state的支持,默認情況下使用URL路徑(而不是哈希片段)。只是打電話history.start時指定它作爲一個選項:

Backbone.history.start({ pushState: true }); 

(請注意,如果您的應用程序位於子路徑域下,那麼你可以告訴骨幹使用,作爲根 - Backbone.history.start({pushState: true, root: "/myapproot/"}) - 雖然它看起來不像你的情況。)