I am separating my views and router into separate files with require. I then have a main.js file that instantiates the router, and also renders my default view.
My router has view ('View/:id') and edit ('Edit/:id') as routes. In main.js, when I instantiate the router, I can hardcode router.navigate('View/1', true) and the navigation works fine. In my view file, when I click on the edit link, I want to call router.navigate('View/' + id, true), but I'm not sure how I should do this.
I've had success calling Backbone.history.navigate('View/' + id, true), but I don't feel like I should be relying on the global Backbone object.
I tried passing ({ router: appRouter }) to my views so I could use this.options.router.navigate(), however that wasn't working for me.
In case you're curious, here's a bunch of code from my app:
Router:
define(['./View', './Edit'], function (View, Edit) {
return Backbone.Router.extend({
routes: {
'View/:id': 'view',
'Edit/:id': 'edit'
},
view: function (id) {
var model = this.collection.get(id);
var view = new View({ model: model });
view.render();
},
edit: function (id) {
var model = this.collection.get(id);
var edit = new Edit({ model: model });
edit.render();
}
});
});
View:
define(function () {
return Backbone.View.extend({
template: Handlebars.compile($('#template').html()),
events: {
'click .edit': 'edit'
},
render: function () {
//Create and insert the cover letter view
$(this.el).html(this.template(this.model.toJSON()));
$('#View').html(this.el);
return this;
},
edit: function () {
Backbone.history.navigate('Edit/' + this.model.id, true);
},
});
});
I have a new solution for routing AMD modules.
RequireJS Router https://github.com/erikringsmuth/requirejs-router
This takes the approach of lazy loading AMD modules as you navigate to each page. With the Backbone router you need to require all of your views as dependencies up front. This loads all of your apps Javascript on the first page load. The RequireJS Router lazy loads modules as you navigate to each route.
Example main.js used to run your app
What about this approach? As backbone implements the template pattern in all its 4 components, with a little of design you can provide to each view an easy navigation mechanism through the app's router without needing to make any circular reference (this was something I saw in other similar posts, but try to avoid it).
Router component, not to much different from other router examples:
App, creates the router instance and fires the first view passing this instance:
BaseView, base constructor definition for all views and also a navigation method:
A View instance, each view extends from the base one instead of backbone, and inherits base behavior:
It works for me, and also it can be reuse in other projects.