1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET AJAX Programmer’s Reference - Chapter 16 pptx

48 327 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 48
Dung lượng 218,86 KB

Nội dung

Behaviors A behavior is a piece of functionality that can be attached to a DOM element. Therefore a behavior is a means of extending the functionality of the DOM element to which the behavior is attached. Not every behavior can be attached to every DOM element. This chapter will provide you with in-depth coverage of some of the standard ASP.NET AJAX behaviors and help you gain the skills you need to develop your own custom behaviors. What is a Behavior, Anyway? I’ll begin our discussions with the simple page shown in Listing 16-1 . As you can see, this page contains a <span> HTML element that displays the text “Wrox Web Site.” Moving the mouse over this link toggles the CSS class of this <span> element. As the boldface portion of Listing 16-1 shows, the pageLoad method first invokes the $get global JavaScript function to return a refer- ence to the <span> HTML element: var label1 = $get(“label1”); Next, it invokes the $addHandler global JavaScript function to register a JavaScript function named toggleCssClass as an event handler for the mouseover event of the <span> HTML element: $addHandler(label1, “mouseover”, toggleCssClass); Finally, it invokes the $addHandler JavaScript function once more to register the toggleCssClass function as an event handler for the mouseout event of the <span> HTML element: $addHandler(label1, “mouseout”, toggleCssClass); As you can see from the boldface portion of Listing 16-1 , the toggleCssClass function simply invokes the toggleCssClass static method on the DomElement class, passing in the event target, c16.indd 659c16.indd 659 8/20/07 6:15:52 PM8/20/07 6:15:52 PM Chapter 16: Behaviors 660 which simply references the <span> HTML element, and the string that contains the CSS class of interest: function toggleCssClass(domEvent) { Sys.UI.DomElement.toggleCssClass(domEvent.target, “CssClass1”); } Now imagine a situation in which you need to do the same thing with many other span and label HTML elements in your application. You can’t reuse the code shown in the boldface portion of Listing 16-1 because it is tied to the specific <span> element on this specific page in your application. Therefore, you would end up recoding the same logic over and over again in different pages of your application. This introduces two fundamental problems: ❑ You are not able to code this logic once and reuse the same code elsewhere in your application. ❑ Since the implementation of this logic is scattered all around your application, every time you need to enhance this logic or fix a bug you have no choice but to make code changes everywhere it is used. The ASP.NET AJAX client-side framework enables you to capture this logic in a separate component known as a behavior, which can then be attached to any span or label HTML element in your applica- tion. This provides the following two important benefits: ❑ It promotes code reusability. ❑ Since the entire code is confined in a single component, you get to make code changes in a single place and rest assured that these changes will be picked up everywhere in your application that this behavior is used. Listing 16-1: A Page Containing a <span> HTML Element <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <head runat=”server”> <title>Untitled Page</title> <style type=”text/css”> .CssClass1 { background-color: Blue; color: Yellow; font-size: 40px; } </style> <script type=”text/javascript” language=”javascript”> function toggleCssClass(domEvent) { Sys.UI.DomElement.toggleCssClass(domEvent.target, “CssClass1”); } c16.indd 660c16.indd 660 8/20/07 6:15:52 PM8/20/07 6:15:52 PM Chapter 16: Behaviors 661 function pageLoad() { var label1 = $get(“label1”); $addHandler(label1, “mouseover”, toggleCssClass); $addHandler(label1, “mouseout”, toggleCssClass); } </script> </head> <body> <form id=”form1” runat=”server”> <asp:ScriptManager runat=”server” ID=”ScriptManager1” /> <span id=”label1”>Wrox Web Site</span> </form> </body> </html> The Behavior Class The ASP.NET AJAX client-side framework comes with a base class named Behavior whose members define the API that all behaviors must implement in order to act as a behavior in the ASP.NET AJAX applications. Listing 16-2 presents the definition of this base class. Listing 16-2: The Create Static Method of the Component Base Class var $create = Sys.Component.create = function Sys$Component$create(type, properties, events, references, element) { var component = (element ? new type(element): new type()); component.beginUpdate(); if (properties) Sys$Component$_setProperties(component, properties); if (events) { for (var name in events) { var eventHandlers = events[name]; var addEventHandlerMethodName = “add_” + name; var addEventHandlerMethod = component[addEventHandlerMethodName]; addEventHandlerMethod(eventHandlers); } } (continued) c16.indd 661c16.indd 661 8/20/07 6:15:53 PM8/20/07 6:15:53 PM Chapter 16: Behaviors 662 Listing 16-2 (continued) Sys.Application._createdComponents[app._createdComponents.length] = component; if (component.get_id()) Sys.Application.addComponent(component); if (Sys.Application.get_isCreatingComponents()) { if (references) Sys.Application._addComponentToSecondPass(component, references); else component.endUpdate(); } else { if (references) Sys$Component$_setReferences(component, references); component.endUpdate(); } return component; } Note that the Behavior base class derives from the ASP.NET AJAX Component base class: Sys.UI.Behavior.registerClass(‘Sys.UI.Behavior’, Sys.Component); This means that a behavior, just like any other ASP.NET AJAX component, goes through the typical com- ponent life cycle thoroughly discussed in Chapter 7 . Recall that a component’s life cycle begins when the component springs into life and ends when it is finally disposed of. As you can see from Listing 7-22 , the create static method of the Component base class shows different life cycle phases of a component, which are shown again in Listing 16-2 . The main responsibility of the create method is to create, initial- ize, and add a new Component object with the specified characteristics to the current ASP.NET AJAX application. This method takes the following parameters: ❑ type : Contains a reference to the constructor of the component class whose instance is being cre- ated. This means that the clients of your behavior will pass a reference to the constructor of your behavior class to this method as its first argument. ❑ properties : References an object literal, each of whose name/value pairs contains the name and value of a particular property of the Component object being created. Therefore, this object sets the values of your behavior’s properties. ❑ events : References an object literal, each of whose name/value pairs contains the name and event handlers of a particular event of the Component object being created. In other words, this object registers event handlers for the events of your behavior. c16.indd 662c16.indd 662 8/20/07 6:15:53 PM8/20/07 6:15:53 PM Chapter 16: Behaviors 663 ❑ references : References an object literal, each of whose name/value pairs contains the name of a specific property of the Component object being created and the value of the id of the Component object that the property references. This object basically sets the values of those properties of your behavior that reference other ASP.NET AJAX components in the current ASP.NET AJAX application. This means that you can implement custom behaviors containing properties that reference other components. ❑ element : References the DOM element with which the Component object being created is asso- ciated. Therefore, this parameter references the DOM element to which your behavior is attached. The highlighted portions of Listing 16-2 show some of the life cycle phases of your behavior: ❑ Instantiation : This is the phase in which the new operator is invoked on the constructor of your behavior, to instantiate it. ❑ beginUpdate : This is the phase in which the beginUpdate method of your behavior is in- voked. As Listing 16-2 shows, this method is invoked immediately after your behavior is instan- tiated and before the properties of your behavior are set, before any event handlers are regis- tered for the events of your behavior, and before your behavior is added to the current ASP.NET AJAX application. Recall from Listing 7-22 that the Component base class’s implementation of the beginUpdate method simply sets an internal flag named _updating to true to mark the beginning of the updating life cycle phase of your behavior, as shown again in the following code listing: function Sys$Component$beginUpdate() { this._updating = true; } ❑ Your behavior can override the beginUpdate method to perform any tasks deemed necessary before its properties are set, before any event handlers are registered for its events, and before your behavior is added to the current ASP.NET AJAX application. Your behavior’s implementa- tion of the beginUpdate method must call the beginUpdate method of its base class to allow the base class to mark the beginning of the updating life cycle phase of your behavior, as shown in following code fragment: YourBehavior.prototype.beginUpdate = function ( ) { YourBehavior.callBaseMethod(this, ‘beginUpdate’); . . . } ❑ endUpdate : This is the phase in which the endUpdate method of your behavior is invoked. As Listing 16-2 shows, this method is invoked after the properties of your behavior are set, after the client’s event handlers are registered for the events of your behavior, and after your behavior is added to the current ASP.NET AJAX application. Recall from Listing 7-22 that the Component c16.indd 663c16.indd 663 8/20/07 6:15:53 PM8/20/07 6:15:53 PM Chapter 16: Behaviors 664 base class’s implementation of the endUpdate method sets the _updating internal flag to false to mark the end of updating phase of your behavior, calls the initialize method of your behavior, and finally invokes the updated method of your behavior: function Sys$Component$endUpdate() { this._updating = false; if (!this._initialized) this.initialize(); this.updated(); } Your behavior can override the endUpdate method to perform those tasks that must be per- formed before the end of its updating phase is marked and before its initialize method is invoked. However, your behavior’s implementation of the initialize method must invoke the endUpdate method of its base class after performing the previously mentioned tasks: YourBehavior.prototype.endUpdate = function() { . . . YourBehavior.callBaseMethod(this, ‘endUpdate’); } ❑ initialize : This is the phase in which the initialize method of your behavior is invoked. As just discussed, this method is invoked after all properties of your behavior are set, after the client’s event handlers are registered for the events of your behavior, after your behavior is added to the current ASP.NET AJAX application, and after the end of updating phase of your behavior is marked. The Component base class’s implementation of the initialize method simply sets an internal flag named _initialized to mark your behavior as initialized: function Sys$Component$initialize() { this._initialized = true; } However, your behavior can override this method to perform its behavior-specific initialization tasks. Your behavior’s implementation of the initialize method must invoke the initialize method of its base class to allow the base class to initialize itself and to mark your behavior as initialized. ❑ updated : This is the phase in which the updated method of your behavior is invoked. As just discussed, this method is invoked after all properties of your behavior are set, after the client’s event handlers are registered for the events of your behavior, after your behavior is added to the current ASP.NET AJAX application, after the end of updating phase of your behavior is marked, and after its initialize method is invoked. Recall from Listing 7-26 that the Component base class’s implementation of the updated method does not do anything. function Sys$Component$updated() { } c16.indd 664c16.indd 664 8/20/07 6:15:54 PM8/20/07 6:15:54 PM Chapter 16: Behaviors 665 However, your behavior can override this method to perform post-update tasks — that is, the tasks that must be performed after all properties of your behavior are set, after the client’s event handlers are registered for the events of your behavior, after your behavior is added to the cur- rent ASP.NET AJAX application, after the end of the updating phase of your behavior is marked, and after its initialize method is invoked. Your behavior, like any other ASP.NET AJAX component, inherits the following methods from the Component base class: ❑ get_events : This getter method returns a reference to the EventHandlerList object that contains all the event handlers registered for the events of the component. Therefore, if you’re writing a cus- tom behavior that needs to expose a new type of event, follow these steps to implement the event: ❑ Implement a new method named add_eventName (where eventName is a placeholder for the name of your event, whatever it may be) as follows to allow the clients of your behav- ior to register event handlers for this event: function add_eventName (eventHandler) { var events = this.get_events(); events.addHandler(“eventName”, eventHandler); } As you can see from the preceding code listing, the add_eventName method first calls the get_events method that your behavior automatically inherits from the Component base class to return a reference to the EventHandlerList object. Then it invokes the addHandler method on this object to register the specified event handler for your event. ❑ Implement a new method named remove_eventName (where eventName is a placeholder for the name of your event) as follows to allow the clients of your behavior to unregister event handlers: function remove_eventName (eventHandler) { var events = this.get_events(); events.removeHandler(“eventName”, eventHandler); } Again, as you can see from the preceding code listing, the remove_eventName method first calls the get_events method that your behavior inherits from the Component base class to return a reference to the EventHandlerList object. Then it invokes the removeHandler method on this object to remove the specified event handler from the list of event handlers registered for your event. ❑ Implement a new ASP.NET AJAX event data class named EventNameEventArgs (where EventName is a placeholder for the name of your event) if necessary. As discussed in previ- ous chapters, every event is associated with a class known as an event data class whose instances hold the event data for the event. c16.indd 665c16.indd 665 8/20/07 6:15:54 PM8/20/07 6:15:54 PM Chapter 16: Behaviors 666 ❑ Implement a new method named _onEventName (where EventName is a placeholder for the name of your event) that takes a single argument of type EventNameEventArgs , as follows, to raise your event: function _onEventName (eventNameEventArgs) { var events = this.get_events(); var handler = events.getHandler(“eventName”); if (handler) handler(this, eventNameEventArgs) } ❑ Note that this method first calls the get_events method inherited from the Component base class to return a reference to the EventHandlerList object. Then it invokes the getHandler method on this object, passing in the name of your event to return a reference to a JavaScript function whose invocation automatically invokes all the event handlers registered for your event. Next, it invokes this JavaScript function and consequently all the event handlers registered for your event. Note that the _onEventName method passes two parameters to each event handler, the first referencing your behavior and the second the EventNameEventArgs object that contains the event data for your event. ❑ get_id : This getter method allows the clients of your behavior to return its id property value. Recall that the id property value is a string that uniquely identifies your behavior in the current ASP.NET AJAX application. ❑ set_id : This setter method allows the clients of your behavior to set its id property value. ❑ get_isInitialized : This getter method returns a Boolean value that specifies whether your behavior has been initialized. (Your behavior is considered initialized when its initialize method has already been invoked.) Note that this method simply returns the value of the _initialized flag: function Sys$Component$get_isInitialized() { /// <value type=”Boolean”></value> return this._initialized; } ❑ get_isUpdating : This getter method returns a Boolean value that specifies whether your behavior is being updated. (Note that this method simply returns the value of the _updating flag.) function Sys$Component$get_isUpdating() { /// <value type=”Boolean”></value> return this._updating; } ❑ add_disposing : This method allows the clients of your behavior to register event handlers for the disposing event of your behavior. As you can see, your behavior automatically inherits this event from the Component base class. Recall that a component raises this event when it is about c16.indd 666c16.indd 666 8/20/07 6:15:54 PM8/20/07 6:15:54 PM Chapter 16: Behaviors 667 to be disposed of, to allow its clients to perform final cleanup and to release the resources they’re holding. ❑ remove_disposing : This method allows the clients of your behavior to remove event handlers from the list of event handlers registered for the disposing event of your behavior. ❑ add_propertyChanged : This method allows the clients of your behavior to register event han- dlers for the propertyChanged event of your behavior. As you can see, your behavior automat- ically inherits this event from the Component base class. Recall that a component raises this event when one of its properties changes value. ❑ remove_propertyChanged : This method allows the clients of your behavior to remove items from the list of event handlers registered for the propertyChanged event of your behavior. ❑ dispose : As the following code listing shows, the Component base class’s implementation of the dispose method first raises the disposing event of your behavior and consequently invokes the event handlers that the clients of your behavior have registered for the disposing event of your behavior, to allow these clients to perform final cleanup and to release the resources they’re holding before your behavior is disposed of. Second, the dispose method deletes the EventHandlerList object that contains the event handlers registered for the events of your behavior before your behavior is disposed of. Third, it calls the unregisterDisposableObject method on the Application object that represents the current ASP.NET AJAX application, to unregister all the disposable objects registered with the application. (Recall that disposable objects are objects whose types implement the IDisposable interface.) If these objects are not unregistered, their dispose methods will be automatically invoked when the application is disposed of, even though your behavior has already been disposed of. Fourth, it calls the removeComponent method on the Application object to remove your behavior from the current ASP.NET AJAX application. function Sys$Component$dispose() { if (this._events) { var handler = this._events.getHandler(“disposing”); if (handler) handler(this, Sys.EventArgs.Empty); } delete this._events; Sys.Application.unregisterDisposableObject(this); Sys.Application.removeComponent(this); } Your behavior can override the dispose method to perform final cleanup and to release the resources it is holding when it is about to be disposed of. It is very important that your behavior’s implementation of the dispose method call the dispose method of its base class. Otherwise, none of the previously-mentioned tasks will be performed. ❑ raisePropertyChanged : If your behavior exposes properties of its own that can change value, and if you believe that the clients of your behavior should be informed when these properties change value, the setters of these properties must invoke the raisePropertyChanged method. As you can see from the following code listing, the Component base class’s implementation of this method invokes the event handlers registered for the propertyChanged event, passing in the PropertyChangedEventArgs object that contains the name of the changed property. c16.indd 667c16.indd 667 8/20/07 6:15:54 PM8/20/07 6:15:54 PM Chapter 16: Behaviors 668 This allows those clients of your behavior that have registered event handlers for the propertyChanged event of your behavior to be notified when the properties of your behavior change value. function Sys$Component$raisePropertyChanged(propertyName) { /// <param name=”propertyName” type=”String”></param> if (!this._events) return; var handler = this._events.getHandler(“propertyChanged”); if (handler) handler(this, new Sys.PropertyChangedEventArgs(propertyName)); } As you can see from Listing 16-3 , the constructor of the Behavior base class takes a single parameter that references the DOM element to which a behavior attaches. This constructor assigns this parameter to a private field named _element . Note that the constructor adds the behavior to a custom collection property on this DOM element named _behaviors . As the name suggests, the _behaviors collection of a DOM element contains references to all behaviors attached to the DOM element. As you can see, you can attach more than one behavior to the same DOM element. Listing 16-3: The ASP.NET AJAX Behavior Base Class Sys.UI.Behavior = function Sys$UI$Behavior(element) { /// <param name=”element” domElement=”true”></param> Sys.UI.Behavior.initializeBase(this); this._element = element; var behaviors = element._behaviors; if (!behaviors) element._behaviors = [this]; else behaviors[behaviors.length] = this; } Sys.UI.Behavior.prototype = { _name: null, get_element: Sys$UI$Behavior$get_element, get_id: Sys$UI$Behavior$get_id, get_name: Sys$UI$Behavior$get_name, set_name: Sys$UI$Behavior$set_name, initialize: Sys$UI$Behavior$initialize, dispose: Sys$UI$Behavior$dispose } Sys.UI.Behavior.registerClass(‘Sys.UI.Behavior’, Sys.Component); Properties The ASP.NET AJAX Behavior base class exposes the properties discussed in the following sections. c16.indd 668c16.indd 668 8/20/07 6:15:55 PM8/20/07 6:15:55 PM [...]... to access in a generic way via the ASP.NET AJAX type-inspection infrastructure 676 c16.indd 676 8/20/07 6:15:57 PM Chapter 16: Behaviors Listing 1 6-1 5: The descriptor Property of the ClickBehavior Sys.Preview.UI.ClickBehavior.descriptor = { events: [ {name: ‘click’} ] } The click Event Listing 1 6-1 6 encapsulates the typical logic that follows the ASP.NET AJAX event-implementation pattern to implement... and previous chapters, implementing a new event for an ASP.NET AJAX client control requires you to follow the ASP.NET AJAX event-implementation pattern, which involves several steps One of the most common events is the click event If you were to implement this event for several ASP.NET AJAX client controls in your application, you’d end up re-implementing the steps of the same ASP.NET AJAX event implementation... Click Me The ASP NET AJAX Control Toolkit The ASP.NET AJAX control toolkit is a shared-source community project that you can download from the official Microsoft ASP.NET AJAX site at http:/ /ajax .asp.net This toolkit contains a bunch of ASP.NET AJAX. .. chapter because all the code is self-contained 680 c16.indd 680 8/20/07 6:15:58 PM Chapter 16: Behaviors BehaviorBase The BehaviorBase class is the base class for all ASP.NET AJAX toolkit behaviors Listing 1 6-1 9 presents the declaration of the members of this class I’ll discuss the implementation of these members in the following sections Listing 1 6-1 9: The BehaviorBase Class AjaxControlToolkit.BehaviorBase... getBehaviors static method takes a single parameter that references a DOM element and returns a reference to the _behaviors collection (if any) of the DOM element (see Listing 1 6-1 2) Recall that this collection contains references to all behaviors attached to the DOM element 674 c16.indd 674 8/20/07 6:15:56 PM Chapter 16: Behaviors Listing 1 6-1 2: The getBehaviors Method of the Behavior Base Class Sys.UI.Behavior.getBehaviors... _partialUpdateEndRequest : AjaxControlToolkit$TextBoxWatermarkBehavior$_partialUpdateEndRequest, (continued) 687 c16.indd 687 8/20/07 6 :16: 00 PM Chapter 16: Behaviors Listing 1 6-2 7 (continued) get_WatermarkText : AjaxControlToolkit$TextBoxWatermarkBehavior$get_WatermarkText, set_WatermarkText : AjaxControlToolkit$TextBoxWatermarkBehavior$set_WatermarkText, get_WatermarkCssClass : AjaxControlToolkit$TextBoxWatermarkBehavior$get_WatermarkCssClass,... Listing 1 6-2 5: The _partialUpdateEndRequest Method function AjaxControlToolkit$BehaviorBase$_partialUpdateEndRequest(sender, endRequestEventArgs) { /// /// Method that will be called when a partial update (via an UpdatePanel) /// finishes, /// if registerPartialUpdateEvents() has been called /// (continued) 685 c16.indd 685 8/20/07 6 :16: 00 PM Chapter 16: Behaviors Listing 1 6-2 5 (continued)... name is given by the ClientStateFieldID property As Listing 1 6-2 2 shows, these two methods first call the getElementById method to return a reference to the hidden field, and then get or set the value of the value property of this field 682 c16.indd 682 8/20/07 6:15:59 PM Chapter 16: Behaviors Listing 1 6-2 2: The ClientState Property function AjaxControlToolkit$BehaviorBase$get_ClientState () { /// . in a generic way via the ASP. NET AJAX type-inspection infrastructure. c16.indd 676c16.indd 676 8/20/07 6:15:57 PM8/20/07 6:15:57 PM Chapter 16: Behaviors 677 Listing 1 6-1 5: The descriptor Property. for several ASP. NET AJAX client controls in your application, you’d end up re-implementing the steps of the same ASP. NET AJAX event implementation pattern over and over c16.indd 675c16.indd 675. several occasions in this and previous chapters, implementing a new event for an ASP. NET AJAX client control requires you to follow the ASP. NET AJAX event-implementation pattern, which involves

Ngày đăng: 09/08/2014, 06:23

TỪ KHÓA LIÊN QUAN