Optional Routes and Query Strings
Learn how to enable the filtering of contacts using URLs and providing navigation.
We'll cover the following...
Our filtering works great, but we should really have the filtering criterion reflected in the URL. That way, users can bookmark their filters and navigate using the back and forward browser buttons.
Updating the URL with the filter button
First, let’s get the URL updated when we filter. We can add an event listener that will update the URL fragment:
Press + to interact
ContactManager.on("contacts:filter", function(criterion){if(criterion){ContactManager.navigate("contacts/filter/criterion:" + criterion);}else{ContactManager.navigate("contacts");}});
Lines 2–4: If we have a filtering criterion, we add it to the URL fragment.
Lines 5–7: If no criterion is given, i.e., the user wants to display all contacts by clearing the filtering criterion, we simply want the URL fragment to be
#contacts
instead of ...