AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 457


Given the usefulness of this technique, we have added it to the AjaxTCR library with
method AjaxTCR.history.enabledBackGuard([message,immediate]). The method
takes two optional parameters: message, which is a string to add to the confirmation
message, and a Boolean flag immediate, which indicates that this functionality should be
enabled immediately. If not set, the library will not activate the functionality until the first
Ajax request has been sent. This gives the user a chance to directly leave the application if
they haven’t performed any work yet. This use of a “dirty flag” doesn’t have to be solely
based upon the invocation of a request. The enableBackGuard( ) method can be invoked
at any time with an immediate flag if desired; for example, when some keystrokes are
detected in a form field. We show the library code here so you can see just how simple it is.

enableBackGuard: function(message, immediate){
/* if already on just return */
if (AjaxTCR.history._backGuardEnabled)
return;

if (message != null && typeof(message) != "undefined")
AjaxTCR.history._backGuardMessage = message;

if (immediate)
AjaxTCR.history._activateBackGuard();
else
AjaxTCR.history._backGuardEnabled =
AjaxTCR.history.BACK_GUARD_INITIALIZED;
},

_activateBackGuard: function(){
var message = AjaxTCR.history._backGuardMessage;
window.onbeforeunload = function () {return message;};
AjaxTCR.history._backGuardEnabled = AjaxTCR.history.BACK_GUARD_ENABLED;
},

Later, when communication occurs and sendRequest() is called, the safeguard is
applied:

if (AjaxTCR.history._backGuardEnabled == AjaxTCR.history.BACK_GUARD_INITIALIZED)
AjaxTCR.history._activateBackGuard();

At the application level all that is necessary is adding a call to the start-up like so:

AjaxTCR.util.event.addWindowLoadEvent(function () {
selectCategories();
AjaxTCR.history.enableBackGuard();
};);
Free download pdf