I have spent the last 2 weeks learning backbone and related tools as well as writing an application. I have hit a wall with a design issue and would like to know what kind of solutions are available and whether Backbone experts even regard this as an issue.
Problem: I am ending up having to put all my view dependencies in my router.js and am unable to figure out if their is a way around that. Below is the code from my router.js:
// router.js
define([
'jquery',
'underscore',
'backbone',
'text',
'views/landing',
'views/dashboard',
],
function($, _, Backbone, t,LandingView,DashboardView){
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'': 'showLanding',
'projects': 'showProjects',
// Default
'*actions': 'defaultAction'
},
navigate_to: function(model){
alert("navigate_to");
},
showProjects: function() {},
showLanding: function() {},
});
var initialize = function() {
var app_router = new AppRouter;
Backbone.View.prototype.event_aggregator = _.extend({}, Backbone.Events);
// Extend the View class to include a navigation method goTo
Backbone.View.prototype.goTo = function (loc) {
app_router.navigate(loc, true);
};
app_router.on('route:showLanding', function(){
var landing = new LandingView();
});
app_router.on('route:showProjects', function(){
var dashboard=new DashboardView();
});
app_router.on('defaultAction', function(actions){
alert("No routes");
// We have no matching route, lets just log what the URL was
console.log('No route:', actions);
});
Backbone.history.start({pushState: true});
};
return {
initialize: initialize
};
});
router.js includes the LandingView and DashboardView views which in turn fetch the respective templates. The initial route loads the LandingView which has a login template. After logging in, it calls the goTo method of router.js to spawn a DashboardView(). Although this works, I feel that it's a bit ugly. But I can't figure how else to spawn a new DashboardView from LandingView without either directly referencing DashboardView() from inside of LandingView() or from the router.
If I continue doing this via router.js I will end up pulling, directly or indirectly, all my views js files from the router. Sounds a bit ugly!
I looked at Derick Baileys' event aggregator pattern but faced the question of how does the DashboardView subscribe to an event generate by the LandingView if an instance of DashboardView doesn't even exist yet? Someone has to create and initialize it for it to subscribe to an event aggregator, right? And if that someone is the router, do I need to instantiate all the views upfront in the router? That doesn't make sense.