I am trying to achive something like this in backbone js
var AppRouter = Backbone.Router.extend({
routes: {
// MVC like route
':controller': 'defaultRoute',
// MVC like route
':controller/:action': 'defaultRoute',
// MVC like route
':controller/:action/:id': 'defaultRoute',
// MVC like route
':controller/:action/*id': 'defaultRoute'
},
defaultRoute: function (controller, action, id) {
// render view here or
// call another specific route regarding to controller parameter
}
});
var appRouter = new AppRouter;
Backbone.history.start();
So when url is: something.com/#home/index defaultRoute function will get parameters controller="home" and action="index". I am wondering now how to find view (Backbone.View) in folder "controller/home/index" and instantiate dynamically (and render). Also wondering if better approach would be to have Backbone.Router for each "controller" (I am using name "controller" but it is actually "router").
Any ideas?
UPDATE with possible solution!
I ended up with this
// Filename: router.js
define([
'jquery',
'underscore',
'backbone'
], function ($, _, Backbone) {
var AppRouter = Backbone.Router.extend({
routes: {
// MVC like route
':controller': 'defaultRoute',
// MVC like route
':controller/:action': 'defaultRoute',
// MVC like route
':controller/:action/:id': 'defaultRoute',
// MVC like route
':controller/:action/*id': 'defaultRoute'
},
defaultRoute: function (controllerName, actionName, id) {
controllerName = controllerName || Config.Defaults.Controller;
actionName = actionName || Config.Defaults.Action;
require(["controllers/" + controllerName], function (ctl) {
var code = "ctl." + actionName + "();";
eval(code);
});
}
});
var appRouter = new AppRouter;
Backbone.history.start();
});
And sample controller is this
define([
'jquery',
'underscore',
'backbone'
], function ($, _, Backbone) {
return {
index: function () {
console.log("Action: Index");
},
about: function () {
console.log("Action: About");
}
};
});
It works with this sample. Now trying to solve params binding etc. Need more testing.