actually it should not matter where you put your routing code – the only thing that matters is that you can completely control the configuration / startup phase of your app. Ideally the rendering of a specific route / template should kickoff everything that’s necessary for you app to run (routing should not be mixed into the rest of your app code). So the routing layer is like the initiator that decides when your app starts, and what should be rendered. The app itself knows nothing about routing (or that there even is something like
iron-router behind it).
How you can achieve this?
- You need to architect your app code in a way that allows for full configuration and control. You always have to ask: “Would i be able to write an integration test for my complete application where i can configure / startup as many times as i want without much hassle?”
Clean separation of concerns: There is 1.routing (the URL in the browser), 2. layout rendering and 3. your app code. All of these things are completely separated from each other. Your app is just a bunch of templates / supporting UI logic that can be kicked-off by rendering it. It does not know that it is rendered by a routing framework (should work the same way when just putting the template tag somewhere)
Communication patterns: So now you decoupled the various concerns, but how can you glue it all together? The simple answer is events. Every layer of your app dispatches events that speak the language of the respective layer. So if you have a view with a login button you should not put the URL to redirect to a certain route in there, but dispatch an event like
LoginRequested because the view does not know about routes or how the login system actually works – it only knows that the user clicked that button and requests a login. Other parts of your app can then handle this event and take appropriate actions like redirecting to a certain route / rendering a login view etc. The fantastic thing about decoupling in this way is: you have complete control over the process! If your view simply provides a hard link to
/login you have no way to hook into this process of “the user requested to login” – and believe me, there are a lot of scenarios where you first want to check, authenticate or setup things before actually fulfilling such requests.
For a simple example how such a system can look like checkout this TodoMVC application that is built with space:ui
The Space framework was designed from the ground up to organize your app into modular components with a clear configuration / startup phase. If you have any questions we have a nice little community of great devs over in the meteor-space Gitter chat!