2.6. Canceling a Request

The initializeRequest() event alerts you to the fact that a request is about to begin and gives you access to the element responsible for initiating the request. You can examine the state of things and explicitly cancel the request here before it even begins based on other factors. For example, you can query the PageRequestManager object and see if an asynchronous postback is already underway as presented here in Listing 2-25.

Example 2-25. Checking to see if an asynchronous postback is occurring
function initializeRequest(sender, initializeRequestEventArgs) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if(prm.get_isInAsyncPostBack() === true) {
        initializeRequestEventArgs.set_cancel(true);
        alert("canceling event from " +
           initializeRequestEventArgs.get_postBackElement().id);
    }

    initializeCount = initializeCount + 1;
}

That would prevent the new request from starting, but you also might want to abort a request after it has started. Suppose that you included a Cancel button in your page:

<input type="button" onclick="cancelRequest()" value="Cancel Request" />

In the onClick() handler, you could then abort a request that is already underway but not yet completed:

function cancelRequest() {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if(prm.get_isInAsyncPostBack() === true) {
        prm.abortPostBack();
    }
}

You can see in Figure 2-18 that the count of calls to the different event handlers can get out of synch. The number of times the page executed is no longer the same as the number of times the page was loaded. Requests were canceled after the page execution was already started. The endRequest() event is still called for every beginRequest() event invoked. And once the pageLoading() event started, the load finished and the pageLoaded() event was called.

Figure 2-18. Figure 2-18

You can count on getting an endRequest() event if the beginRequest() event is invoked, even if the request is canceled. However, as you have seen, you cannot expect each event for every request initialized. Other factors that skew the lifecycle come into play.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset