Meteor.js Iron Router Filters, Before and After Hooks
##Introduction
The Meteor.js Iron Router is the one package that helps me so much and is the first one I add in every application. If you do not know the Iron-Router make sure to learn how to use it because it realy helps so much!
The Iron Router basically decides what to render for the current Route (URL). Also do not think that you are building a so called one-page app and you do not need urls. You always need urls (e.g. share a state, bookmarking). And even if you are just building a quick prototype, maybe you come up with a feature that people would like to share, so better start with proper urls right from the beginning. But this is just a small part where the Iron Router helps you. One really great feature are the hooks.
##What are Iron Router Hooks?
The Iron Router basically works like this:
A new route is called
The Iron Router checks if there are before hooks and runs them all
If all before hooks are done and ready the rendering takes place
Now the after hooks are all run
That means we can create functions that are run before any route and this is amazing if you for example want to filter a route to be only for logged in users.
##Two ways to implement hooks
###Define it in a route itself
You can create a before hook for exactly one route like this:
I personally would suggest to use this way only if it is a very special before hook that you would never use for any other route. In the example above you filter for logged in users and this is a filter you want to have on many routes. So do not do this in a routes before hook.
###Define it seperated from a specific route
For my hooks I create a seperated file that really is only for hooks and nothing else. This way you can take code out of your Iron Router route-map. Even though the Iron Router routes are capable of a lot of things I personally do not want huge route functions. So I create a new file and define hooks like this:
As we can see, you can specify hooks for certain routes or even globally for any route.
Hook Compilation
There are some hooks I use quite often and I am sure you also have some common hooks. Please feal free to send me hooks you like to use or comment them below so we can gather hooks that are helpful.
Before Hooks Compilation
Dynamic Layout Configuration
This is nice if you have different layouts or different regions that are different many times. I do not like defining the same layoutTemplate and regions (named yields) in every route over and over again. So I use a before hook:
###After Hooks Compilation
###Unload Hooks Compilation
##Conclusion
Hooks are really great and are making things much easier, the code cleaner and better to maintain. I am sure there are a lot more practical hooks out there and I would love to learn how you make use of this Iron Router functionality, so please feel free to comment or contact me.