【发布时间】:2015-10-25 00:59:08
【问题描述】:
我想弄清楚如何在我的 Marionette.js 应用程序中使用路由器和控制器。我可以在我的应用程序的启动处理程序中启动初始页面,但我似乎无法弄清楚如何处理其他路线。这个 SPA 并不复杂,我的用户只有三个页面。一种是潜在客户表视图、车辆表视图和单个车辆的视图。在弄清楚这条路线的工作原理之前,我并不担心单车视图。
// my app
var App = new Marionette.Application({});
// my lead and vehicle model rows
App.vehicleRowView = Marionette.ItemView.extend({
tagName: 'tr',
template: '#vehicle-row-tpl'
});
App.leadRowView = Marionette.ItemView.extend({
tagName: 'tr',
template: '#lead-row-tpl'
});
// composite views for the tables
App.vehicleTableView = Marionette.CompositeView.extend({
tagName: 'div',
className: 'row',
template: '#vehicles-table',
childViewContainer: 'tbody',
childView: App.vehicleRowView
});
App.leadsTableView = Marionette.CompositeView.extend({
tagName: 'div',
className: 'row',
template: '#leads-table',
childViewContainer: 'tbody',
childView: App.leadRowView
});
// controller
var Controller = Marionette.Object.extend({
leads: function() {
var leadstable = new App.leadsTableView({
collection: this.leads
});
App.regions.leads.show(leadstable);
},
vehicles: function() {
console.log('vehicles...');
}
});
// router
var AppRouter = Marionette.AppRouter.extend({
controller: new Controller,
appRoutes: {
'leads': 'leads',
'vehicles': 'vehicles'
}
});
App.router = new AppRouter;
App.vehicles = [];
App.leads = [];
// Start handlers
App.on('before:start', function() {
this.vehicles = new Vehicles();
this.vehicles.fetch();
this.leads = new Leads();
this.leads.fetch();
var appContainerLayoutView = Marionette.LayoutView.extend({
el: '#app-container',
regions: {
vehicles: '#vehicles-content',
leads: '#leads-content'
}
});
this.regions = new appContainerLayoutView();
});
App.on('start', function() {
Backbone.history.start({pushState: true});
var vehiclesLayoutView = new this.vehicleTableView({
collection: this.vehicles
});
App.regions.vehicles.show(vehiclesLayoutView);
});
App.start();
在开始时,首页很好。但是,当我转到#leads 时,我的潜在客户表没有呈现。实际上,路由并没有发生,并且 URL 更改为 /#leads。如果我然后转到该 URL,则呈现表格骨架,但不呈现数据。集合在 before:start 上加载得很好,模板也很好。我必须访问 URL 两次,但该表没有数据,即使我的 App.leads 集合加载正常。不过,我的 console.log 输出确认我正在上路。
当用户转到#leads 路线时,我想隐藏车辆区域。当用户转到#vehicles 时,我想隐藏我的潜在客户表并显示车辆(与我的启动处理程序相同的视图)。
我觉得我就在那里,但缺少一些基本的东西。
【问题讨论】: