Yahoo’s Rich Web UIs for Java Developers

Yahoo’s Rich Web UIs for Java Developers

ahoo User Interface (YUI) is an open source JavaScript library for developing AJAX-based rich user interfaces. The new Yahoo Mail uses YUI, so you might imagine how powerful the library is. This is the first article in a three-part series that primarily targets Java developers who are not JavaScript experts, but are developing web applications with server-side frameworks (such as JavaServer Pages, Struts, or Spring). In this installment, JavaScript novices will see how to use YUI for setup and design , and should learn a good deal about object-oriented JavaScript programming. For developers already expert in JavaScript, this article series serves as an introduction to the YUI library.

The next two articles in the series will cover the following:

  1. Containers, layouts, widgets, event handling, AJAX components, and server-side interaction
  2. DataTable, pagination, sorting, JSON, and error handling

YUI Under the Hood

Essentially, the YUI library is a collection of components that address various aspects of a web application. They broadly fall into the following categories:

  • Controls/Widgets:
    • Container components such as Panel, Tooltip, Dialog, etc.
    • UI widgets such as Button, Calendar, DataTable, Menu, Paginator, Rich Text Editor, etc.
  • Components for interacting with server-side modules
  • Components for dealing with DOM and Event handling
  • Components for managing animation, drag and drop, page layout, etc.

The YUI source code comes in three forms for every component, which is handy for debugging any problem unique to your application:

  • Standard form: You can use this form to understand the implementation of a component.
  • Debug enabled: This form prints debug information.
  • Compressed: This form has white spaces removed to improve download performance.

JavaScript Programming Bugaboos

Developing and debugging JavaScript applications is painful, particularly for Java developers. Errors are not easy to spot, even if you use a JavaScript debugger like Firebug. Consider the following common JavaScript programming pitfalls and their solutions:

  • If you fail to prefix a local variable with the var keyword in a function during declaration, the value is retained outside the function scope. This makes determining what went wrong difficult.
  • Everything in JavaScript is a function, so you must use the new keyword precisely to create an instance of a class. Otherwise, JavaScript invokes the function and assigns the return value to the left operand.
  • Do not suffix the function name with open and closed parentheses when passing a reference to the function. This will actually invoke the function.
  • The column width you pass in to the DataTable component differs between IE and Firefox. Set the column width 20 pixels smaller in Firefox than in IE.
  • JavaScript code behaves differently from browser to browser. So you must test the application in all targeted browsers whenever you make a change to your application.
  • If you use a new YUI component and forget to include the source JavaScript file, you won’t get any error, but the component won’t work. One option is to use YUI Loader to download the source files on demand, but I prefer to link individual source files of the components in use. That way, you can control exactly what gets downloaded?a simple approach very much like importing the necessary classes in a Java program.

YUI’s Object-Oriented JavaScript Design

Until AJAX frameworks emerged, JavaScript was not treated as an application development platform. Despite its support for object-oriented (OO) design, JavaScript was treated merely as a scripting language to implement minimal dynamic web page behavior. To leverage OO design in JavaScript development, YUI uses an object-oriented design in all its components.

The following sections demonstrate OO programming in JavaScript and introduce an approach that will help you structure your classes for OO JavaScript applications. The YUI library provides the components to facilitate this style of development.

Creating Namespaces

In enterprise software, it is very common to group classes based on behavior in a namespace. So it is important to learn about namespaces before learning to create classes and objects.

If you want all your namespaces to fall under the Yahoo namespace, you can create them like this:

YAHOO.namespace("myapp");YAHOO.namespace("myapp.util");YAHOO.namespace("myapp.ui");YAHOO.myapp.Main = function() {}

This code creates three namespaces as well as a class under the namespace YAHOO.myapp.

Alternatively, you can define your own namespace as follows:

if(!DevX) DevX = {};if(!DevX.myapp) DevX.myapp = {};DevX.myapp.Main = function() {}

Managing Files

You can define multiple classes in the same JavaScript file, but it is a good practice to have separate files for them.

Defining Classes

You can define a class in one of two ways: using an object literal or defining a function. Object literals typically are useful for defining classes that contain all static methods and do not need a constructor to initialize. The following code snippets show how to define a Util class using the object literal approach.

Suppose the file util.js contains the following:

if(!DevX) DevX = {};if(!DevX.myapp) DevX.myapp = {};DevX.myapp.Util = {     TIMEOUT : 5, // Timeout constant in minutes for server requests     isBrowserIE : function() {          return > 0;     }}

To use this class, you wouldn’t need to create an instance of Util. You instead would access the members directly:

if(DevX.myapp.Util.isBrowserIE()) {	// IE specific behavior}

Alternatively, you can define a class using a function. Suppose the file main.js has the following contents. Refer to the inline comments to understand the class definition.

if(!DevX) DevX = {};if(!DevX.myapp) DevX.myapp = {};DevX.myapp.Main = function (title) { // Constructor     var t = title; // Private variable	     /**     * Private method     */     function getTitle() {          return t;     }	     /**     * Public method     */     this.refresh = function () {          // Refresh the main page     }};

You can instantiate and use the defined class as follows:

var main = new DevX.myapp.Main('Home page');main.refresh();

As you add more functionality to your class, your constructor would keep growing because all the members are defined within it. To define additional method and fields, you could use the method YAHOO.lang.augment to define your method and fields outside the constructor. Consider how this code adds a login method to the class Main:

YAHOO.lang.augment(DevX.myapp.Main, {     login : function(username, password) {          // perform login operation     }});

Implementing Inheritance

You can implement inheritance by using the utility method YAHOO.lang.extend. Consider subclassing the class Main and changing the behavior of the method refresh.

As an example, the file application main.js has the following contents:

if(!DevX) DevX = {};if(!DevX.myapp) DevX.myapp = {};DevX.myapp.AppMain = function () {     //Call the super class constructor, 'App Main');	     // Derived class specific initialization goes here}YAHOO.lang.extend(DevX.myapp.AppMain, DevX.myapp.Main);DevX.myapp.AppMain.prototype.refresh = function () {     // Modify refresh behavior}

The prototype keyword refers to the structure of the class.

Web Application Design

At this point, a Java developer may have a couple of questions regarding the myapp example. Does using YUI eliminate the need to write HTML? Is this library like the Java Swing API? Sorry, but the answer to both questions is “No.” The previously described application uses HTML pages for its basic UI elements. However, every page will be backed by JavaScript code, which uses YUI and other JavaScript libraries as the application demands. YUI handles events raised by the page’s UI elements, interaction with the AJAX server, pagination, and so on.

Table 1 offers class design principles for your web applications. Assuming your application has two pages, and each page has various UI elements, the HTML and JavaScript classes should work as described in Table 1.

Table 1. HTML and JavaScript Classes for Your Application
HTML and JavaScript Classes Description
/cxt/page1/Page1.html UI elements, layout
/cxt/page1/page1.css Style sheet for page1
/cxt/page1/page1.js Main class for page1. Initialize components, register events, deal with method callbacks, and perform server interaction.
/cxt/page1/page1_util.js Utility methods applicable to page1
/cxt/page1/page1_datatable.js Abstraction of a DataTable instance used in page1
/cxt/page2/Page2.html UI elements and layout for page2
/cxt/page2/page2.js Main class for page2
/cxt/shared/js/util.js Common utility methods
/cxt/shared/js/myapp-datasource.js Customized DataSource
/cxt/shared/js/myapp-connection.js Customized server connection class
/cxt/shared/css/myapp-table-skin.css CSS properties for DataTable

If your application is more complicated than simple pages with a rich user interface, you should probably consider a different strategy for the class design.

More to Come

You now should have an understanding of what YUI can contribute to your applications, the OO design approach for developing web pages and classes, best practices for developing with JavaScript, and how to write your own classes and inherit a class to modify a behavior.

The next installment builds on this knowledge with an examination of YUI layouts, basic widgets, event handling, and server interaction. Stay tuned.



Share the Post:
Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic