Thursday, January 29, 2009

Ajax.History

Ajax.History provided features

Three parameters are provided by Ajax.History allowing you to configure the browsing history manager.
A callback has also been introduced: onStateChange(string state).
This callback is launched when the state of the browsing history points to the request.
This allows for example to change the title of the page according to the state (see example below).

Ajax.History.Request

Ajax.History.Request used exactly as Ajax.Request of Prototype.
For an interactive example, we create a simple function:
function ajaxHistoryRequest(url, myState)
{
new Ajax.History.Request(url, {
history : {
id : 'example',
state : myState,
cache : true,
onStateChange: function(state) {
// change title
History.setTitle(History.getTitle() + ' - Page Ajax #' + state);
}
},
onSuccess: function(transport) {
$('box-example').update(transport.responseText);
// some stuff
}
});
ajaxHistoryRequest('history/request1', 'first-test');
ajaxHistoryRequest('history/request2', 'second-test');
ajaxHistoryRequest('history/request3', 'third-test');
** The cache is enabled, if you use a module as FireBug on Firefox, you can see that the use of buttons back/forward of your browser does not reload the Ajax.Request.

Ajax.History.Updater

Ajax.History.Updater used exactly as Ajax.History.Request :
Automatic historyId :
Here, the historyId is not declared, the 'containerName' is used automatically.
new Ajax.History.Updater('containerName', 'my/url/to/load.html', {
history : {
cache : true
}
});

// location.href == '...#containerName={state}'
Disable historyCache :
The cache is disabled, so, when user perform back/forward of browser, the Ajax Request will be loaded whenever.
new Ajax.History.Updater('containerName', 'my/url/to/load.html', {
history : {
id : 'my-own-identifier',
cache : false
}
});

// location.href == '...#my-own-identifier={state}'
Ajax.Cache

How does the cache?
Ajax.Cache can "simulate" an Ajax Request from an Ajax Request made beforehand. It takes only one argument: the object Ajax.Request / Updater create first.
In fact, Ajax.Cache is based on a modified prototype Ajax.Request API. Yes, to simulate the request, I remove the mechanism (real) sending the HTTP request.
Perform simulation manually :
Ajax.Cache is already implemented in Ajax.History.* classes. However, you can use it manually :
// the request is executed firstly
var request = new Ajax.Request('my/url/to/load.html', {
method: 'POST',
...
});

// reproduced the Ajax.Request without HTTP request
new Ajax.Cache(request);
http://www.prototypextensions.com/history

No comments: