在Backbone.js中获取URL片段而不是散列

jba*_*ban 2 javascript router url-routing backbone.js

很长一段时间我一直在努力解决这个问题.我正在使用Backbone.js和Require.js.我试图告诉Backbone根据当前的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
    }
  });
Run Code Online (Sandbox Code Playgroud)

所以基本上当用户访问http://example.com/new_page时,它应该记录<code>hej</code>,当他访问http://example.com/editpage时,它应该记录<code>ho</code>.我不知道如何实现这一点,即使有可能.谁能帮我?

McG*_*gle 8

您可以使用Backbone对HTML5推送状态的支持,默认情况下使用URL路径(而不是散列片段).只需在调用时将其指定为选项history.start:

Backbone.history.start({ pushState: true });
Run Code Online (Sandbox Code Playgroud)

(请注意,如果您的应用程序位于域下的子路径中,那么您可以告诉Backbone将其用作根目录Backbone.history.start({pushState: true, root: "/myapproot/"})- 尽管在您的情况下看起来不是一个问题.)