My perspective on HTML5 pushstate may differ from the traditional understanding.
Push-state functionality simply enables capturing changes in the browser's URL, which would typically prompt a server request. It does not solely provide "forward" and "back" events but rather offers general "location change" events. Therefore, it becomes your application's responsibility to interpret the URL changes and determine the user's intended destination.
Consider this scenario: Imagine a user clicks a link within your application that requires handling via JavaScript. You would have event handlers set up to intercept the click and modify the application accordingly. Navigating "back" or "forward" acts similarly to clicking a link, except you receive only the target URL – without any associated links to bind event handlers to.
So, how do you ascertain the user's intent? You could manage state using global variables or devise alternative methods. To minimize code repetition, managing all app routing through URLs is an option. Thus, instead of binding specific links (or sets of links) to click handlers, you monitor URL changes and adapt based on the new URL.
In BackboneJS, a Router object achieves this by linking specific paths to corresponding router functions, adjusting the app state accordingly:
MyAppRouter = Backbone.Router.extend({
routes: {
'home': 'setupHomeScreen',
'recipes': 'setupRecipesList',
'recipes/:id': 'setupRecipeScreen'
},
setupHomeScreen: function() {
// ...
},
setupRecipesList: function() {
// ...
},
setupRecipeScreen: function(id) {
// ...
},
// ...
});
Apologies for including Backbone code in an Angular-related query. As I transition from a background in Backbone, this context shapes my understanding of pushstate.
To address your query
If your views exhibit some hierarchical structure, consider storing this information in a global variable. For instance, assigning IDs to each view and appending these IDs to an array whenever the browser state changes could be a strategy:
var viewHistory = [];
// ... user navigates to the recipe list; include in history
viewHistory.push('recipeList');
// ... user visits a specific recipe; add to history
viewHistory.push('recipe:13');
// ... user hits the "back" button. The URL indicates a desire
// to return to the recipe list, but direction (backward/forward) is unclear.
var nextView = 'recipeList';
if (viewHistory.indexOf(nextView) > 0) {
// *** Back Button Clicked ***
// Assuming no nested recipeList under another recipeList in the hierarchy
animateBack(nextView);
// Remember to remove 'recipeList' from the history
viewHistory.splice(viewHistory.indexOf(nextView), viewHistory.length);
} else {
// *** Arrival via other means ***
animateForward(nextView);
}