遇到Marionette JS路由器问题

时间:2015-10-29 13:19:47

标签: javascript backbone.js marionette backbone-routing

我的路由器和控制器出了问题。在我的应用程序before:start上,我有一个处理程序,可以获取潜在客户和车辆的集合。

我有一个区域,我的布局视图为:

var App = new Marionette.Application({});

var AppLayoutView = Marionette.LayoutView.extend({
  el: 'body',
  regions: {
    main: '#app-container'
  }
});

我的控制器是:

var Controller = Marionette.Object.extend({
    leads: function() {
      App.regions.main.show(new App.leadsTableView({collection: App.leads}));
    },
    vehicles: function() {
      App.regions.main.show(new App.vehiclesTableView({collection: App.vehicles}));
    }
});

在我的启动处理程序中:

App.on('start', function() {
  App.regions = new AppLayoutView();
  App.router = new Marionette.AppRouter({
    controller: new Controller(),
    appRoutes: {
      'leads': 'leads',
      'vehicles': 'vehicles'
    }
  });

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

App.start();

如何从特定路线开始?并且,当用户访问#vehicles时,如何让该区域加载新视图?我错过了关于路由器的一些信息。

编辑:当我转到我的网址中的#leads时,我的车辆视图出现了。当我点击转到#leads和#vehicles的链接时,它们不起作用。

1 个答案:

答案 0 :(得分:1)

默认路线

您可以通过添加" splat"来定义默认值。路线(以*开头的路线)到路线的末端。我喜欢使用*default来明确意图:

appRoutes: {
  'leads': 'leads',
  'vehicles': 'vehicles',
  '*default': 'leads'
}

断开链接

由于您使用的是pushstate路由,因此视图网址为/vehicles,而不是哈希片段#vehicles。您不应再使用散列片段网址。

这是一种通过链接点击触发pushState路线的简单方法:

$('a[href]').on('click', function(e) {
  e.preventDefault();
  var href = e.target.getAttribute('href');
  App.router.navigate(href, { trigger: true })
});

您可能会发现此post about moving from hash fragment to pushState routing有用。

您还需要将服务器配置为将与您的路线匹配的请求传递到主应用页面 - 例如,它需要了解http://localhost/app/vehicle应由http://localhost/app处理。