A topic that comes up quite often in Ember.js discussion forums is optional route parameters. Unfortunately for those who have this problem, there's no built-in way to achieve this functionality. But there is a very nice little hack that will emulate optional route parameters for most sitautions. The actual method is pretty simple, it just requires combining a few tricks. I'll describe the high-level deatils here, and you can find working example code below.
What's needed to pull this off:
- You'll need a resource with a sub-route. The sub-route is the 'real' route that you're going to use. All of your logic should be declared in the controller and template for this route. (Also remember that using a resource generates an implicit
index
route.) - The implicit
index
route is where you should redirect to if you have no model to provide. It's also where you end up if you go to a URL without providing the parameter. This route immediately redirects to your other sub-route usingnull
as the model. (Do not useundefined
, Ember will work differently if you do.) - The sub-route that has all of the logic has a check in the
model
hook to return anull
model if there was no route parameter provided. - The sub-route that has all of the logic also overrides the
serialize
hook. It checks for an empty model and puts an empty string in the URL instead of puttingundefined
in the URL.
That's really all there is to it. Just know that if you need to go to your page without a model, send the user to the index
route. If you have a model, transition to the other sub-route (the id
sub-route in our case). You shouldn't have to do anything with the index
sub-route except redirect to the other sub-route.
Note: For those of you using Ember CLI, I've made comments showing which files these classes belong in.