Dynamic routing is a section of the path for a route which changes based on the content of a page. Instead of having multiple routes for similar pages we have one route that changes state accordingly. Dynamic routing is extensively used in the Open Event Front-end application, for tables, events & other pages.
Sometimes we might need to have multiple dynamic routes for a particular route in this case we need to do implement a custom route redirection. Let’s see how did we implement it in the events route?
Dynamic routes in events route
The events route has two dynamic subroutes view & list. By default the dynamic route which is declared at the last will be used by ember which is list route in this case. This leads to loss of the view route which uses the ID of the event to display the event details.
Here event_id is the ID of an event from the API response, event_state is the state of the list of events created by the user. The event_id is an alphanumeric value which is dynamic in nature and event_state is a string value which is a static value. Due to non overlapping states we can implement a simple procedure that enables us to create multiple dynamic routes.
Implementing multiple dynamic routing in ‘events’ route
As both the subroutes use different states i.e event_id & event_state, we can use this to redirect the routes accordingly. We will add a beforeModel() function in the events/list route and check if the eventState is not equal to live, draft or past which are the states of list route.
If the ‘eventState’ is not in the array we redirect the page to the events.view route using the replaceWith() function. This will ensure that the events.view route is not lost & the event details are rendered properly.
Thank you for reading the blog, you can check the source code for the example here.
- Dynamic models in routes https://guides.emberjs.com/v2.3.0/routing/specifying-a-routes-model/
- Methods of ember routes https://www.emberjs.com/api/ember/2.14/classes/Ember.Route/methods/beforeModel?anchor=beforeModel