我正在尝试使用require.js以模块化方式开发backbone.js应用程序 我想为每个模块分别使用路由器,因此需要路由器中的“baseURL”:
var Router=Backbone.Router.extend({
baseUrl:'user',
routes:{
"":"loaduserProfile", // should open at url
"search":"searchUsers", // should open at url + baseUrl
},
为此,我正在考虑使用一些自定义包含来扩展backbone.prototype.route:
route: function(route, name, callback) {
//CUSTOM CODE
route = this.baseUrl + route;
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
callback && callback.apply(router, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
}
这是实现这个目标的正确方法吗?
答案 0 :(得分:0)
在这种情况下,最好使用Backbone.RouteManager。
例如:
// SubRouter.js
define(function ( require ) {
return Backbone.Router.extend({
routes: {
"": "index",
"test": "test"
},
index: function() {
window.alert("SubRouter navigated successfully");
},
test: function() {
window.alert("sub/test triggered correctly");
}
});
});
// MainRouter.js
define(function ( require ) {
var SubRouter = require( 'path/to/SubRouter' );
return Backbone.RouteManager.extend({
routes: {
// Define a root level route
"": "index",
// Define a sub route
"sub/": SubRouter
},
index: function() {
window.alert("MasterRouter navigated successfully");
}
});
});
require(['path/to/MainRouter'], function (AppRouter) {
// Create a new instance of the app router
app.router = new AppRouter();
// Trigger the test route under sub
app.router.navigate("sub/test", true);
});
答案 1 :(得分:0)
看看https://gist.github.com/tbranyen/1235317。 我使用类似的东西作为模块的子程序系统,其中每个模块基本上是可以插入或拔出的应用程序的功能。