Here's some example pseudo-code that would switch an Ajax email
interface in between different view states based on a hash change. It
would show either the inbox or the form for creating a new message. If
you had saved a message draft, it could also repopulate the various
form fields from saved data.
function showInbox() {
document.getElementById("emailsubmitform").hide();
document.getElementById("emailinbox").show();
}
function createMessage(isDraft, historyData) {
document.getElementById("emailinbox").hide();
document.getElementById("emailsubmitform").show();
if (isDraft) {
var form = document.getElementById("messageForm");
form.toField.value = historyData.toField;
form.fromField.value = historyData.fromField;
form.subjectField.value = historyData.subjectField;
form.messageField.value = historyData.messageField;
}
}
var yourListener = function(newLocation, historyData) {
switch(newLocation) {
case "inbox":
showInbox();
break;
case "newMessage":
createMessage();
break;
case "draftMessage":
createMessage(true,historyData);
break;
}
}
Of course, none of this would work if you didn't have matching logic
in all of your various calls to history.add(). Continuing pseudo-code
from the example above, we'd attach the following listener functions
to the various buttons in our interface.
inboxButtonDOMElement.onclick = function() {
showInbox();
history.add("inbox", null);
}
newMessageButtonDOMElement.onclick = function() {
createMessage();
history.add("newMessage", null);
}
saveDraftButtonDOMElement.onclick = function() {
var form = document.getElementById("messageForm");
var formData = form.serializeJSON();//a function that serializes the
values of a form's fields into a JSON object;
history.add("draftMessage",formData);
showInbox();
}
Does all this make sense? Your calls to history.add need to create the
history points; your history listener consumes them. Each history
point can contain just a newLocation (for simple things like
viewstates) or both a newLocation and additional historyData for more
complex data storage and retrieval. In the real world, of course, this
example is a little spurious because users can have more than one
email draft saved, and they'd expect those drafts to be saved to the
server across sessions rather than merely saved short-term on the
client. Still, this should demonstrate the correct way to use RSH
listeners and add() calls.