I’ve been working on my own version of the Sage theme for a while now,
customising it to suit my basic project needs.
The Sage implementation of DOM-based Routing is excellent,
but for larger projects I like to split the routing to be one class/route per file
##My solution
1. Every route has it’s own JS file: assets/scripts/routing/example.js contains:
var routingExample = {
// All pages with body class 'example'
'example': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
}
};
2. Every route’s JS file is added as a file dependency: assets/manifest.json contains the following main.js dependency, before scripts/main.js:
I’m very new to Sage (also, not really experienced in javascript) and I’m trying to figure out the best way to write maintainable JS.
I feel like yours is a great solution, with only one problem: since I need to use jQuery in my script I have to wrap my extras.js’s code in an anonymous function “(function($) { … })(jQuery);”.
This also means I won’t be able to access the variables I define on that file in the main.js router. Is there any way to solve this?
This is really only relevant to Sage 8, where routing took place in a single file. In Sage 9, there is a routes directory, in which you can declare your route-based JS in separate files and import into a main.js file.