I've got a page with some select-fields. Once the user changes the value of a select-field, a new history-object is created using the values of all select-fields as a state object:
$(".chosen-select-field").chosen().change(function() {
$(".chosen-select-field").each( function ( index ) {
parameterNames[index].value = $( this ).val();
});
history.pushState(parameterNames, '', newUrl);
});
parameterNames is an array of objects containing a key and value e.g.
parameterNames.push({key:"name", value:"foobar"});
The following code restores the state when the user clicks on the back or forward-button in the browser. It works but behaves unexpectedly.
For example, I change three select-fields (creating three history entries). Then I go back. restoreState is executed, one select-field is changed accordingly. But the browser itself remains at the same position in history (can't go forward, still the same number of back-history entries).
Then I click again on the back button. This time the state-object is the same as the one delivered the list time I clicked. The browser moves back one entry in the history though.
The third time I click on the back button the next select-field is changed but the browser stays again at the state unless I click a 4th time.
Can anyone explain what I'm doing wrong?
var restoreState = function(event) {
event = event.originalEvent;
parameterNames = event.state;
$(".chosen-select-field").each( function ( index ) {
if ($( this ).val() != parameterNames[index].value){
$( this ).val(parameterNames[index].value).change();
$( this ).trigger('chosen:updated');
}
});
};
// Bind history events
$(window).bind("popstate",restoreState);