Search⌘ K
AI Features

Optional Routes and Query Strings

Explore how to implement optional routes and query strings to filter contact collections in a Marionette.js app. Learn to update URL fragments dynamically to reflect filtering criteria, enabling bookmarking and navigation with browser buttons. Understand how to parse URL parameters to apply filters and display the criteria in the user interface, enhancing app state management and user experience.

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:

Node.js
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 ...