Translation: Valens
Time: 2007-06-11
Original text: http://ajax.asp.net/docs/overview/AJAXClientEvents.aspx
Everyone is welcome to make comments and I will actively make modifications!
Introduction [Introduction]
Microsoft Ajax proposes client-side life cycle events similar to the server-side life cycle events of ASP.NET 2.0 pages. These client-side events allow us to customize our user interface for both traditional postbacks and asynchronous postbacks (partial page refreshes). They can also help you manage and use custom scripts throughout the page lifecycle.
These client-side events are proposed in Microsoft's AJAX Libray class (we can find them in the AJAX Libray class). These classes are automatically instantiated (instantiated?) when loading a server control with AJAX. These classes provide some APIs so that we can bind events to event provider handlers. And the AJAX Library is browser-independent, so the code you write will work in all supported browsers.
The key events are the load event of the application instance that initiates the request and the asynchronous postback. When the script is run during the load handler event, all scripts and components have been loaded and are available. When part of the page is refreshed using the UpdatePanel control, the most critical of all client events is the PageRequestManager class. These client-side events enable you to implement certain scenarios. Examples include: Undoing postbacks, setting a higher priority for a postback, and making the UpdatePanel interact better when refreshing.
These events are very helpful for us to create pages or write components. If you are a web developer, you can use custom scripts for loading and unloading of pages.
To learn more about server-side life cycle events, you can refer to ASP.NET Page Life Cycle Overview.
Client Classes [Client Classes]
in the Microsoft AJAX class library proposes two main classes in the client life cycle of AJAX web pages. : Application class and PageRequestManager class.
The Application class is instantiated when the browser requests a page that contains a ScriptManager control. The Application class is similar to the server-side Page control. It also inherits from the Control class, but it has some additional functions (compared to server-side events). Similarly, Application inherits the Sys.COmponent class. In addition, it also provides many operable events during the client life cycle.
If a page contains a ScriptManager and one or more UpdatePanel controls, then the page can achieve partial update effects. In that case, an instance of the PageRequestManager class is available to the browser. The client events provided by PageRequestManager are all about asynchronous postback. For more details on generating partial pages, please refer to: Partial-Page Rendering Overview.
Adding Handlers for Client Events [Add Handler for client events]
Now add or remove events by using the add_eventname and reomve_eventname methods in the Application and PageRequestManager classes. The following example shows how to add a handler named MyLoad to the Application object's init event.
Sys.Application.add_init(MyInit);
function MyInit(sender) {
}
Sys.Appplication.remove_init(MyInit);
Comment; This example only shows the syntax of using the add_eventname and remove_eventname methods. More details on using this event are provided in a later topic.
Handling the Application Load and Unload Events [Operation Application's load and unload events]
To operate the Application object's load and unload events, there is no need to explicitly bind to an operation event. Instead, you can create a function directly using the reserved keywords pageLoad and pageUnload. The following example shows how to add an action to the Application's load event.
function pageLoad(sender, args) {
}
Events for Other Client Classes [Other Client Classes]
This topic only describes events provided by the Application and PageRequestManager classes. Microsoft's AJAX class library also includes the following classes for adding, clearing, and removing DOM element events. These classes include:
There is the Sys.UI.DomEvent.addHandler method or shorthand $addHandler.
There is the Sys.UI.DomEvent.clearHandlers method or shorthand $clearHandlers.
There is the Sys.UI.DomEvent.removeHandler method or shorthand $removeHandler.
Events provided by DOM principles are not discussed in this topic.
Client Events of the Application and PageRequestManager Classes [Client events of the Application and PageRequestManager classes]
The following table lists the client events of the Application and PageRequestManager classes that you can use in AJAX ASP.NET pages. The sequence of events will be discussed in a later topic.
Event
(event name)
Description
(describe)
initEvent
[Initialization event]
This event is raised after all scripts have been loaded and before any objects are created. If you plan to write a component (script), the init event provides a point in the life cycle to add the component (script) to the page. This component can be called by other scripts in the life cycle. If you are a web developer, in most cases, it is recommended to use the load event instead of the init event.
The init event is only created once when the page starts to be generated. Subsequent partial page refreshes will not trigger the init event.
load event
[loading event]
This event is raised after all scripts have been loaded and after all program objects initialized with $create have been created. This event will be raised by all postbacks to the server, including asynchronous postbacks.
If you are a web developer, you can create a function called pageLoad, which is provided by the load event itself. The pageLoad operation (handler) can be called after any operation that is added to the load event through the add_load method.
The load event requires a Sys.ApplicationLoadEventArgs object as the eventargs parameter. You can use this parameter to decide whether the page needs to display a partial refresh, and you can also decide which components should be created after the last load event was fired.
unload Event
[Uninstall event]
Raised before all objects are released and before the browser's window.unload event occurs.
You can handle the unload event through a function called pageUnload provided by the system itself. The pageUnload event is called when the page is unloaded in the browser. During this event, we should release all resources occupied by the code.
propertyChanged Event
[Attribute change event]
Raised when a component's properties change. The application object inherits this event from the Component class. This event is only raised when the developer calls the Sys.Component.raisePropertyChange method when setting a property value.
See Defining Custom Component Properties and Raising PropertyChanged Events for more information.
Property change events require a Sys.applicationLoadEventArgs object as the eventargs parameter.
disposing Event
[release event]
This event is raised when the application instance is released. The application object inherits this event from the Component class.
initializeRequest Event
[Initialization request event]
This event occurs at the beginning of an asynchronous request. You can use this event to cancel a traditional postback, for example to allow an asynchronous postback to take precedence.
The initialize request event requires an eventargs parameter provided by the Sys.WebForms.InitializeRequestEventArgs object. This object provides useful elements of objects that cause postbacks and underlying requests. This event also exposes the cancel attribute. If you set cancel to true, a new postback will be canceled.
beginRequest Event
[Start request event]
This event is raised before an asynchronous postback to the server begins. If a postback process already exists, it will be stopped (by using the abortPostBack method). You can use this event to set request headers or display an interesting (animation) prompt on the page to indicate that the request is in progress.
This event requires a Sys.WebForms.BeginRequestEventArgs object as the eventargs parameter. This object provides useful elements for causing postbacks and underlying request objects.
pageLoading Event
[Page loading event]
Raised before any content on the page is updated when an asynchronous postback has been received by the server. You can use this event to provide a custom transition effect for content that needs to be updated.
This event requires a Sys.WebForms.PageLoadingEventArgs object as the eventargs parameter. This object provides useful information about which panels will be deleted and updated as a result of the most recent asynchronous postback.
pageLoaded Event
[Page load complete event]
Raised after all content of the page has been refreshed by a synchronous or asynchronous postback result. During synchronous postback, panels can only be created, but during asynchronous postback, panels can be created and updated. You can use this event to manage a custom change effect for content that needs to be updated.
This event requires a Sys.WebForms.PageLoadedEventArgs object as the eventargs parameter. This object provides useful information about which panels were updated and created during the most recent postback.
endRequest Event
[end request event]
Raised after an asynchronous postback has been completed in response and the page has been updated, or after an error occurred during the request. If an error occurs, the page will not be updated. Use this event to provide a customized error message to visitors or log in the error log.
This event requires a Sys.WebForms.EndRequestEventArgs object as the eventargs parameter. This object provides some useful information about the error that was raised and whether the error was handled. It also provides available information about the corresponding object.
Event Order Example [Event Order Example]
The following example shows how client-side events will be raised on a page with two nested UpdatePanel controls. Please note the difference between clicking the button in the parent panel and the button in the embedded panel. The button in the parent panel will cause the parent panel to be updated, and the panel embedded within it will be deleted and recreated. Buttons with embedded panels only cause updates to the embedded panel.
Page code:
1<%@ Page Language="C#" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
4 " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
5
6<script runat="server">
7
8</script>
9
10<html xmlns=" http://www.w3.org/1999/xhtml " >
11<head runat="server">
12 <title>Client Event Example</title>
13 <style type="text/css">
14 #OuterPanel { width: 600px; height: 200px; border: 2px solid blue; }
15 #NestedPanel { width: 596px; height: 60px; border: 2px solid green;
16 margin-left:5 px; margin-right:5px; margin-bottom:5px;}
17 </style>
18</head>
19<body>
20 <form id="form1" runat="server">
21 <div>
22 <asp:ScriptManager ID="ScriptManager1" runat="server">
23 <Scripts>
24 <asp:ScriptReference Path="ClientEventTest.js" />
25 </Scripts>
26 </asp:ScriptManager>
27 <asp:UpdatePanel ID="OuterPanel" UpdateMode="Conditional" runat="server">
28 <ContentTemplate>
29 Postbacks from inside the outer panel and inner panel are
30 asynchronous postbacks. PRM = Sys.WebForms.PageRequestManager. APP = Sys.Application.
31
32 <br /><br />
33 <asp:Button ID="OPButton1" Text="Outer Panel Button" runat="server" />
34 Last updated on
35 <%= DateTime.Now.ToString() %>
36 <br /><br />
37
38 <asp:UpdatePanel ID="NestedPanel" UpdateMode="Conditional" runat="server">
39 <ContentTemplate>
40 <asp:Button ID="NPButton1" Text="Nested Panel 1 Button" runat="server" />
41 Last updated on
42 <%= DateTime.Now.ToString() %>
43 <br />
44 </ContentTemplate>
45 </asp:UpdatePanel>
46 </ContentTemplate>
47 </asp:UpdatePanel>
48
49 <input type="button" onclick="Clear();" value="Clear" />
50
51 <asp:Button ID="FullPostBack" runat="server" Text="Full Postback" />
52 <a href=" http://www.microsoft.com">Test Window Unload</a>
53 <br />
54 <span id="ClientEvents"></span>
55 </div>
56 </form>
57</body>
58</html>
59
script code:
1// Hook up Application event handlers.
2var app = Sys.Application;
3app.add_load(ApplicationLoad);
4app.add_init(ApplicationInit);
5app.add_disposing(ApplicationDisposing);
6app.add_unload(ApplicationUnload);
7
8
9//Application event handlers for component developers.
10function ApplicationInit(sender) {
11 var prm = Sys.WebForms.PageRequestManager.getInstance();
12 if (!prm.get_isInAsyncPostBack())
13 {
14 prm.add_initializeRequest(InitializeRequest);
15 prm.add_beginRequest(BeginRequest);
16 prm.add_pageLoading(PageLoading);
17 prm.add_pageLoaded(PageLoaded);
18 prm.add_endRequest(EndRequest);
19}
20 $get('ClientEvents').innerHTML += "APP:: Application init. <br/>";
twenty one}
22function ApplicationLoad(sender, args) {
23 $get('ClientEvents').innerHTML += "APP:: Application load. ";
24 $get('ClientEvents').innerHTML += "(isPartialLoad = " + args.get_isPartialLoad() + ")<br/>";
25}
26function ApplicationUnload(sender) {
27 alert('APP::Application unload.');
28}
29function ApplicationDisposing(sender) {
30 $get('ClientEvents').innerHTML += "APP:: Application disposing. <br/>";
31
32}
33//Application event handlers for page developers.
34function pageLoad() {
35 $get('ClientEvents').innerHTML += "PAGE:: Load.<br/>";
36}
37
38function pageUnload() {
39 alert('Page:: Page unload.');
40}
41
42// PageRequestManager event handlers.
43function InitializeRequest(sender, args) {
44 $get('ClientEvents').innerHTML += "<hr/>";
45 $get('ClientEvents').innerHTML += "PRM:: Initializing async request.<br/>";
46}
47function BeginRequest(sender, args) {
48 $get('ClientEvents').innerHTML += "PRM:: Begin processing async request.<br/>";
49}
50function PageLoading(sender, args) {
51 $get('ClientEvents').innerHTML += "PRM:: Loading results of async request.<br/>";
52 var updatedPanels = printArray("PanelsUpdating", args.get_panelsUpdating());
53 var deletedPanels = printArray("PanelsDeleting", args.get_panelsDeleting());
54
55 var message = "-->" + updatedPanels + "<br/>-->" + deletedPanels + "<br/>";
56
57 document.getElementById("ClientEvents").innerHTML += message;
58}
59function PageLoaded(sender, args) {
60 $get('ClientEvents').innerHTML += "PRM:: Finished loading results of async request.<br/>";
61 var updatedPanels = printArray("PanelsUpdated", args.get_panelsUpdated());
62 var createdPanels = printArray("PaneslCreated", args.get_panelsCreated());
63
64 var message = "-->" + updatedPanels + "<br/>-->" + createdPanels + "<br/>";
65
66 document.getElementById("ClientEvents").innerHTML += message;
67}
68function EndRequest(sender, args) {
69 $get('ClientEvents').innerHTML += "PRM:: End of async request.<br/>";
70}
71
72// Helper functions.
73functionClear()
74{
75 $get('ClientEvents').innerHTML = "";
76}
77function printArray(name, arr)
78{
79 var panels = name + '=' + arr.length;
80 if(arr. length > 0)
81 {
82 panels += "(";
83 for(var i = 0; i < arr.length; i++)
84 {
85 panels += arr[i].id + ',';
86}
87 panels = panels.substring(0, panels.length - 1);
88 panels += ")";
89 }
90 return panels;
91}
92
Running effect View code
Event Order for Common Scenarios [General event order]
The order of event triggering still depends on what controls are used in the page and what type of request occurs (initialization request, traditional postback or asynchronous postback). This section describes the event request sequence for several common scenarios.
Initial Request [Initialization request]
During a page initialization request, a small number of client events are triggered. Assume that the following is the scenario of the initialization request.
· The page includes a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering properties are both true.
· The request is of GET type;
· The server can respond normally.
Here is the sequence in which events occur on the client side:
1. An initialization request occurs to the server.
2. The client receives the response.
3. The Application instance triggers the init event.
4. The Application instance triggers the load event.
The initialization event occurs only once during the entire page life cycle when the application is instantiated. It will not be raised by subsequent asynchronous postbacks. During the initial request (note the request), no PageRequestManager events are raised.
Asynchronous Postback [Asynchronous postback]
An asynchronous postback sends some page data to the server, receives a server-side response, and then refreshes part of the page. Assume the following asynchronous postback scenario:
· The page includes a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering properties are both true.
· There is an UpdatePanel control on the page, and the value of the ChildrenAsTriggers property of the control is changed to true.
· There is a button inside the UpdatePanel for triggering an asynchronous postback.
· Successfully obtain response from server side.
Here is the sequence in which events occur on the client side:
1. When clicking the button in the UpdatePanel control, an asynchronous postback is caused.
2. The PageRequestManager instance triggered the initializeRequest event.
3. The PageRequestManager instance triggered the beginRequest event.
4. The request is sent to the server.
5. The client receives the response.
6. The PageRequestManager instance triggered the pageLoading event.
7. The PageRequestManager instance triggered the pageLoaded event.
8. The Application instance triggered the load event.
9. The PageRequestManager instance triggered the endRequest event.
Please note that the application's load event is after the PageRequestManager's pageLoaded event and before the endRequest event.
Multiple Asynchronous Postbacks [Multiple Asynchronous Postbacks]
When a previous request is running on the server or browser and the user sends a new request, multiple asynchronous postbacks occur. Assume that the following scenario describes the case of multiple asynchronous postbacks.
· The page includes a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering properties are both true.
· The page contains an UpdatePanel control.
· In the UpdatePanel, a button control that causes an asynchronous postback is clicked twice. The second click occurs while the server is processing the request initiated by the first click.
· Obtained the response to the first request returned from the server.
Here is the sequence in which events occur on the client side:
1. Clicking the button in the UpdatePanel triggers an asynchronous postback.
2. The PageRequestManager instance triggered the initializeRequest event.
3. The PageRequestManager instance triggered the beginRequest event.
4. The request is sent to the server.
5. The client receives the response.
6. The button is clicked again, triggering a second asynchronous postback.
7. The PageRequestManager instance triggers the initializeRequest event for the second click.
8. The PageRequestManager instance triggers the beginRequest event for the second click.
9. The second click request of Northern Expedition scanned the server.
10. The client receives the response of the second click.
11. The PageRequestManager instance triggered the pageLoading event.
12. The PageRequestManager instance triggered the pageLoaded event.
13. The Application instance triggered the load event.
14. The PageRequestManager instance triggered the endRequest event.
The default asynchronous postback behavior is that the most recent asynchronous postback takes precedence. If two asynchronous postbacks occur in sequence and the first asynchronous postback is still being processed by the browser, the first asynchronous postback is canceled. If the first postback has been sent to the server, the server will not return the first request until the second request arrives. For more details on how to set priority for asynchronous postback, please refer to Giving Precedence to a Specific Asynchronous Postback.
Browsing Away from a Page [Browsing other pages]
When the user accesses other pages from one page, the current page will be displayed from the browser Unload, so you can operate the unload event to release resources. Suppose this scenario is simulated below.
· The page includes a ScriptManager control, and the control's SupportsPartialRendering and EnablePartialRendering properties are both true.
· The target page exists.
Here is the sequence in which events occur on the client side:
1. Initiate a request for a new page.
2. The browser gets a response requesting a new page.
3. The Application instance triggers the unload event.
4. A new page is displayed.
If an error occurs when requesting a new page, the unload event will still be raised, but the new page will not be displayed.
【over】