好吧,我想出了一个适用于每个区域的路由器解决方案。可以通过路线图和视图轻松配置路由器。当路线匹配时,最初通过的区域将显示视图的新实例。
Here https://gist.github.com/eskimoblood/4995526是路由器的高级版本,其中路由参数将传递到视图中。
Update
仅当每条路线仅注册一次时,上述解决方案才有效。如果您第二次注册相同的路由,则第一次的回调将被覆盖。所以我想出了一个解决方案,区域控制器不直接在路由器上注册路由,而是监听route:change
全局事件总线(Marionette.Application.vent)上的事件,并且路由器触发route:change
此事件总线上的事件。
路由器控制器:
// The problem with backbone router is that it can only register one function per route
// to overcome this problem every module can register routes on the RouterController
// the router will just trigger an event on the `app.vent` event bus when ever a registered routes match
define(function() {
function RouterController(vent) {
this.vent = vent;
this.router = new Backbone.Router();
}
RouterController.prototype = _.extend({
//just pass the route that change you wanna listen to
addRoutes: function(routes) {
_.each(routes, function(route) {
this.router.route(
route,
_.uniqueId('e'),
//create a closure of vent.trigger, so when ever the route match it simply trigger an event passing the route
// _.partial(_.bind(this.vent.trigger, this.vent), 'route:change', route)
_.bind(function() {
this.vent.trigger.apply(this.vent, ['route:change', route].concat(_.toArray(arguments)));
}, this)
);
}, this);
}
},
Backbone.Events);
return RouterController;
});
区域路由器:
define(['common/App'], function(app) {
function RegionRouter(region, routerSettings) {
app.router.addRoutes(_.keys(routerSettings));
this.listenTo(app.vent, 'route:change', function() {
var route = arguments[0];
var View = routerSettings[route];
if (!View) {
return;
}
var params;
if (arguments.length > 1) {
params = computeParams(arguments, route);
}
region.show(new View(params));
});
}
RegionRouter.prototype = _.extend(
{
onClose: function() {
this.stopListening(app.vent);
}
}, Backbone.Events
);
function computeParams(args, route) {
args = Array.prototype.slice.call(args, 1);
//map the route params to the name in route so /someroute/:somevalue will become {somevalue: passedArgs}
//this object will be passed under the parameter key of the options
var params = {};
var regEx = /(?::)(\w+)/g;
var match = regEx.exec(route);
var count = 0;
while (match) {
params[match[1]] = args[count++];
match = regEx.exec(route);
}
return {params: params};
}
return RegionRouter;
}
);