Writing Object-Oriented JavaScript Part 3


Part 1 of this series described the object-orientedfeatures of JavaScript. Part 2 built upon thatknowledge and introduced a framework supporting class inheritance. In this finalinstallment, we’ll use Cfx to construct a JavaScript control classhierarchy that offers rich client-side behaviors to ASP.NET user controls.


A web control represents a portion of the web page that typically providesuser interaction such as text boxes, radio buttons, check boxes, etc. Webcontrol can be static as well. Subdividing pages into controls improvesabstraction by making pages containers of web controls and enhances reuse andextensibility.

With ASP.NET, you can use conventional HTML elements or ASP.NET controls. Youcan augment them with defining your own user controls. Eventually ASP.NETrenders all controls into HTML and JavaScript interpreted by the client browser.Naturally, you can write your website and use the default ASP.NET behaviors.However this is not feasible in all situations and limits the user experience.Using Cfx you can now achieve greater control and richness to yourclient-side scripts writing object-oriented JavaScript.

Note – A detail explanation of ASP.NET and web controls is beyond thescope of this article as there are many great books and essays on ASP.NET. Theaim of this article is to show how Cfx is used to build classesthat take advantage of ASP.NET to build rich clients.

The Strategy

Leveraging ASP.NET Control Names

ASP.NET applies a consistent naming scheme to its controls using theid and name attributes when it renders them as HTMLelements. ASP.NET names HTML elements using the element name proceeded by thenames of its containers separated by an underscore. For example, in accompanyingdemo, the ASP.NET CfxText user control encapsulate the ASP.NETtextbox control giving it the identifier txtField.

The ASP.NET CfxText user control has the id txtNameand is subsequently encapsulated by a CfxWebFormOptions controlwith the id CfxWebFormOption1. The id generated by ASP.NET for theHTML text element uses the outermost container identifier followed by theseparator character continuing with the name of the next container and thenfinally followed with the control identifier.

By leveraging this naming convention, we can logically group control elementsand develop a class hierarchy of ASP.NET control wrappers in JavaScriptproviding client side behavioral support to the ASP.NET user controls.

Note – ASP.NET 2.0 uses a dollar sign ($) character as the separatorcharacter. The dollar sign eliminates ambiguities caused by the underscoreseparator where it can be used in identifiers.Cfx.Dom.GetElementTerms uses a regular expression that accounts forunderscore ambiguities when splitting ASP.NET identifiers into element terms.

The JavaScript Control Class Hierarchy

CfxControl conceptually represents the set of user controlclasses used on the page. These classes represent a layout description alongwith its client side behavioral definition. The layout description is definedusing ASP.NET and maintained in the accompanying .aspx and.cs files. The client side behaviors are written in JavaScript incorresponding .js files. Thus client behavior is separated from itslayout. Notice that we have nearly a one-to-one correspondence between therendering files and the JavaScript files. The additional JavaScript filescontain common base class definition and implementation defined in theCfxControl and CfxInput classes.

At the top level of the JavaScript control class hierarchy is theObject class followed by the CfxControl class and isthe root of all JavaScript controls. The CfxWebFormOptions controlis the container class for the input controls on the WebForm1 page.There are three input controls deriving specific functionality from theCfxInput class. The CfxText class represents acontrol for text input. The CfxSelect class represents a singleselection dropdown and CfxLabel wraps the ASP.NETLabel control. CfxRadioSet represents a group of radioelements. The CfxHistoryOptions class contains theCfxRadioSet and the CfxSelect classes providing asingle control for making “historical” selections.

A couple of helper classes that are not part of the CfxControlheirarchy are provided. The CfxError class extends theError class adding the framework object throwing the exception andthe CfxEvent wrapper for JavaScript event objects.

Figure 1. CfxControl class hierarchy.

JavaScript Client-side Controls


The CfxControl class is the base class for all derived controlsand encapsulates properties inherited by all controls. The name property is thename of control. Think of controls as document element containers and it is thename of the container the name property represents. Theparent property is the parent CfxControl. The itemsproperty is an array of document elements that has the control name as part ofits id attribute.

Figure 2. ASP.NET control identifier and terms.

For example when theCfxWebFormOptions control named CfxWebFormOptions1 iscreated, all the elements and images in the document that contains the stringCfxWebFormOptions1 in the id attribute are added tothe items array of the CfxControl.


The CfxInput class is the base class for input controls. Thisclass defines input controls as having an input element propertyelement and an image property image indicating theerror state of the input control. It defines several base methods to manipulatethe image property and an Initialize and Validatemethod. CfxInput is not defined as an abstract class and can beinstantiate. This is useful for situations needing a generic input controlobject.


The CfxText control wraps the text input element and validatesits input against the regExp regular expression property. The control alsoprovides the ability to sink the onkeypress event inspecting for anthe enter key to start validation. Users provide a handler in the event theenter key is pressed via the CfxText controlSubmitHandler method.

Figure 3. Setting SubmitHandler of txtName control to OnEnterKey handler.

If the submit handler is supplied, during the text input elementonkeypress event, execution is transferred to theCfxText control OnEnterKey method. TheCfxEvent class wraps the JavaScript event object and inspects forthe enter key event. If the enter key event was pressed, theOnEnterKey method calls CfxText submit handler.

Figure 4. CfxText OnEnterKey event handler.

Fired by the onkeypress event, OnEnterKey methodthis reference does not refer to a CfxText instancebut to the event source element. FindInstance is used to obtain theinstance of CfxText associated with the source element. In orderfor FindInstance to determine the instance, theCfxText.instance flag is set to true in its classdefinition.


The CfxSelect control wraps a single selection dropdown inputelement providing method to add and delete elements to and from the dropdown.CfxSelect also provide accessors methods to obtain the selectedtext and value as well as the index of the selected element.


The CfxLabel wraps the ASP.NET Label controlproviding an interactive way of alterting page text. ASP.NET renders its labelsas span elements and CfxLabel locates it through itsid attribute constructed by appending together the names of itsancestor controls. The Value accessor updates the inner text ofthe span element. Rather than using alerts, CfxLabel can be usedto enhance the display of error notifications.


The CfxRadioSet control wraps a group of radio input elements.ClickHandler method sets the onclick event handler ofthe radio button elements. GetElement returns theCfxRadioSet radio button element from the radio button index.GetIndex returns the index of the CfxRadioSet radiobutton element. The GetItems method inherited fromCfxControl is overridden by CfxRadioSet, because radioelements are grouped by the name attribute while the base methoduses the id attribute to find elements. TheGetSelected method returns the checked radio element, andLength returns the number of radio elements inCfxRadioSet.


This control provides the client-side functionality of the set of elementsthat simulate selecting history criteria. This control provides thefunctionality for the CfxRadioSet control and the controlsassociated with the radio buttons.

Figure 5. CfxHistoryOptions user interface.

CfxHistoryOptions groups the control into aCfxRadioSet control containing of a list of the radio elements aswell as the radio element affiliations. For example the radioSetproperty contains the radio elements: radDefault,radByMonth, and radByYear. The radByMonthradio input element affiliate is the CfxSelect control namedradByMonth_selByMonth control and radByYear radioinput element affiliate is the radByYear_selByYear control. TheradDefault radio element has no affiliates. The valueattribute of the radio element identifies affiliates thusCfxHistoryOptions class can group elements containing that value.In this case radByMonth radio input affiliation consists of theelements radByMonth radio and radByMonth_selByMonthdropdown.

Figure 6. Grouping radio element affiliate controls.

During initialization, CfxHistoryOptions establishes on anonclick event handler for the radio set. When a radio element isclicked the OnRadioClick handler is called altering the disablestate of the radio affiliates. Notice that the handler uses theCfxEvent class FindInstance method toobtain the instance of the CfxHistoryOptions class from the eventsource element. Finally, the Validate method verifies selections.

Cfx Wrapper Classes


This wrapper class augments the JavaScript Error object adding aproperty that references the instance of the Cfx class throwing theexception. As you will see in the demo, the thrown CfxError objectis used identify and change the state of the throwing CfxText object.


The CfxEvent class is a wrapper for JavaScriptevent objects. The event object contains theinformation about JavaScript events and passed along to CfxControlevent handlers. CfxEvent hides browser variations of theevent object providing a consistent interface. In the demo,CfxControl event handlers are responsible for detecting the enterkey event, the radio button check event, and the submit button click event. Thehandlers create a CfxEvent object to wrap the eventobject and calls FindInstance to translate the element firing theevent into its corresponding CfxControl instance.

Code In Front

The final implementation of the controls occurs in the JavaScript of theWebForm1 page. When WebForm1 loads, theonload event calls the page’s OnLoad functioninstantiating a new CfxWebFormOptions control and assigns it toformOptions. The SubmitHandler method assigns theOnSubmit event handler that gets called when the control submitbutton click event occurs or the enter key is pressed from a text control.OnSubmit then calls the Validate method and performs apostback if the validation succeeds.

Figure 7. WebForm1 page code in front are now trivial routines.


Cfx performs surprisingly well. The demo program includes alertsdisplaying page load and submission performance. For a 2GHz system, the time foreach task was under 35 milliseconds for IE 6.0 and under 50 milliseconds forMozilla 1.4.


The ControlDemo demo program, shows how to design and implementa control class heirarchy using Cfx. The approach to thisapplication is to have ASP.NET responsible for the page layout and JavaScriptresponsible for client-side user interactions.

The URL for this application ishttp://localhost/JsOOP/ControlDemo/WebForm1.aspx. Copy the source codeinto the JsOOP/ControlDemo subdirectory of yourhttp://localhost home directory. You can use Visual Studio to createthe ASP.NET project or use the IIS management tool found in Administrative Toolsof the Control Panel. This demo has been tested on both version 1.0 and 1.1 ofthe runtime.


This series on object-oriented programming in JavaScript is an attempt tofill in an astonishing gap in the development of client-side scripts. Too oftenscripts are written as procedural adjuncts rather than as reusable objects. Muchof the reason for this, has to do with JavaScript books simply failing to fullyexplain the language’s object-oriented capabilities and no intrinsic support ofclass inheritance. Another contributing factor is ASP.NET itself where theprogramming model suggests writing JavaScript as procedural adjuncts for ASP.NETcontrols.

Cfx, provides an easy to use coding pattern for writing classhierarchies in JavaScript. The result of writing object-oriented scripts isricher client-side functionality by having JavaScript take on greaterresponsibility of UI management. While ASP.NET defines page layout, the codebehind becomes trivial enabling the server-side code to be better focused on thebusiness logic.

On the other hand it may be useful to have the ASP.NET controls emitJavaScript. Using Cfx you can still structure your scripts in anobject-oriented fashion. Cfx is quite versitile letting you choosethe deployment that works best for you.

Another advantage of Cfx is that it enables you as a webdeveloper to retain greater control of your code. ASP.NET is powerful but toomuch reliance on any tool from a single vendor can spell trouble when targetingmultiple platforms and browsers. Cfx, because it isobject-oriented, makes it easy to isolate idiosyncrasies in façades andwrappers. While the demos are written for ASP.NET, Cfx is aJavaScript framework that is not specific to ASP.NET.

I hope that the JavaScript Class Framework elevates the quality ofclient-side scripts promoting rich web-based interfaces, reduce vendordependencies, and promote the building of a collection of reusable JavaScriptclasses.

Resource: Codeproject

Leave a Reply

Your email address will not be published. Required fields are marked *