1

I have routes like this:
category/keyword/id

A user can navigate like this:
category/science/42
category/science/13
category/science/39
category/publishing/38
category/publishing/91
category/publishing/3

Moving back and forward in history works exactly like it should, but I would like to implement a back-button that takes the user back to the previous category. So that if the user is at the last route above (/publishing/3) and clicks that button, I want to send the user back to /science/39.

Is there a way to use Backbone.history to go back to a specific point based on the URL at that time?

L42
  • 3,052
  • 4
  • 28
  • 49

1 Answers1

1

The easiest solution here is probably storing the history yourself as suggested here. Backbone.history is not really querable for history content: Get previous router/url in backbone application

A function for navigating to last matching route without same "category" with history defined as in the linked answer would be:

function getCategory(fragment) {
    return fragment.split("/")[1];
}

function goBackToLastMatchingRouteOfOtherCategory() {
    var reversedHistory = history.reverse();
    var currentCategory = getCategory(Backbone.history.getFragment());
    for (var historyIndex in reversedHistory) {
        var historyFragment = reversedHistory[historyIndex].fragment;
        if (getCategory(historyFragment) !== currentCategory) {
            router.navigate(historyFragment, {trigger: true});
            return true;
        }
    } 
    # No matching route with other category found in history
    return false;
}

You did not specify how you want the app to react when the user haven't navigated to other categories, so I did not include that in my answer.

Community
  • 1
  • 1
torkil
  • 111
  • 5