示例2
我们的第2个例子是一个简单的模拟ajax email 应用的示例,叫O'Reilly Mail,类似Gmail. O'Reilly Mail描述了怎样使用dhtmlHistory类去控制浏览器的历史,和怎样使用historyStorage对象去缓存历史数据。
O'Reilly Mail 用户接口(user interface)有两部分。在页面的左边是一个有不同email文件夹和选项的菜单,例如收件箱,草稿,等等。当一个用户选择了一个菜单项,比如收件箱,我们用这个菜单项的内容更新右边的页面。在一个实际应用中,我们会远程取得和显示选择的信箱内容,不过在O'Reilly Mail里,我们简单的显示选择的选项。
O'Reilly Mail使用Really Simple History 框架向浏览器历史里加入菜单变化和更新地址栏,允许用户利用浏览器的回退和前进按钮对应用做书签和跳到上一个变化的菜单。
我们加入一个特别的菜单项,地址簿,来描绘historyStorage 能够怎样被使用。地址簿是一个由联系的名字电子邮件和地址组成的javascript数组,在一个真实的应用里我们会取得他从一个远程的服务器。不过,在 O'Reilly Mail里,我们在本地创建这个数组,加入几个名字电子邮件和地址,然后把他们存储在historyStorage 对象里。如果用户离开了这个web页面以后又返回的话,O'Reilly Mail应用重新从缓存里得到地址簿,胜过(不得不)再次访问远程服务器。
地址簿是在我们的初始化initialize()方法里存储和重新取得的
/** Our function that initializes when the page
is finished loading. */
function initialize() {
// initialize the DHTML History framework
dhtmlHistory.initialize();
// add ourselves as a DHTML History listener
dhtmlHistory.addListener(handleHistoryChange);
// if we haven't retrieved the address book
// yet, grab it and then cache it into our
// history storage
if (window.addressBook == undefined) {
// Store the address book as a global
// object.
// In a real application we would remotely
// fetch this from a server in the
// background.
window.addressBook =
["Brad Neuberg 'bkn3@columbia.edu'",
"John Doe 'johndoe@example.com'",
"Deanna Neuberg 'mom@mom.com'"];
// cache the address book so it exists
// even if the user leaves the page and
// then returns with the back button
historyStorage.put("addressBook",
addressBook);
}
else {
// fetch the cached address book from
// the history storage
window.addressBook =
historyStorage.get("addressBook");
}
处理历史变化的代码是简单的。在下面的代码中,当用户不论按下回退还是前进按钮 handleHistoryChange 都被调用。我们得到新的地址(newLocation) 使用他更新我们的用户接口来改变状态,通过使用一个叫displayLocation的O'Reilly Mail的工具方法。
