Followup on YUI : getFirstDescendantBy()

Awhile ago I posted on an additional function for YAHOO.util.Dom called getFirstDescendantBy(). I was following the ticket submitted to the YUI Sourceforge tracker, and saw that it had been closed out, and that a new function called YAHOO.util.Dom.getElementBy() was added to fill this request. I decided to check out the newly available YUI source code on github, and noticed some nice enhancements. YAHOO.util.Dom.getElementBy(method, tag, root) is now available (not in the latest stable release yet though), and does what getFirstDescendantBy did, and in most cases its much faster. Great job to the YUI team!

Instead of taking a recursive approach to walking the graph like I had, YUI is just grabbing all the children by tag name, even if you don’t supply a tag name (in this case it will use ‘*’). This turns out to be much faster than the recursive approach for most cases. If you happen to be looking for an element in a very large dom tree structure, and that object is located early on in the tree, the new YUI approach will be slower than the recursive approach. Fortunately, when I say “large” dom tree, I’m talking about a tree about 8 nodes deep, iterated 500-1000 times. Most of us don’t work with sites displaying that much html on a single page, so its definitely not a concern in my book.

Digging in further, I noticed that the new getElementBy just delegates to YAHOO.util.Dom.getElementsBy(), which has now been improved to accept a number of additional parameters than what 2.6.0 has available. One of those is a boolean, firstOnly, which will stop after it finds the first match, and return it. It looks like there are also additional parameters for passing in an object to your apply method, and making that object the scope.

I’m excited about this change, and it means I will soon be able to use the native YUI function for what I needed. I’d suggest that anyone else that was using something such as the getFirstDescendantBy() that I had shared look at switching once YUI releases the new function. Thanks again YUI.

  • del.icio.us
  • Digg
Tagged , | 1 Comment

Javascript widget approaches: Singleton vs Prototype

Recently I’ve been doing some work setting up some standard javascript widgets for a web application I am working on. By widget, I’m referring to items such as javascript date pickers, tooltips, autocomplete inputs, etc. I’m building on top of YUI for this approach, but the principles I’d like to discuss are applicable to any library. YUI provides a fantastic javascript library, and a collection of widgets right out of the box. More than likely, as you add them to your application, you’ll want to wrap or extend them in your own javascript implementations to get them functioning as desired. To accomplish this, I typically have taken one of two approaches, and these are the topic I’d like to cover. To provide a working example, I’ll use a simple wrapper for a YUI Calendar widget that is linked to a text input, and opens by clicking a calendar icon.

image of a date picker widget

Prototype approach

This approach basically creates an instance of the javascript widget for each input field, and the javascript widget object utilizes the prototype definition so the internal functions can be defined once in memory. Below is an example of what a simple DatePicker widget that “wraps” the YUI Calendar widget, would look like:

function DatePicker(icon, field) {
    this.icon = icon;
    this.field = field;
    YAHOO.util.Event.addListener(window, 'load', this.initialize, this, true);
}
DatePicker.prototype = {

	icon : null,

	field : null,

	calendar : null,

	id : 'date-calendar',

	container : null,

	initialize : function() {
		YAHOO.util.Event.addListener(this.icon, 'click', this.click, this, true);
		this.renderContainer();
	},

	renderContainer : function() {
		this.container = document.createElement('div');
		this.container.style.display = 'none';
		document.body.appendChild(this.container);
	},

	click : function(e) {
		if(this.calendar === null) {
			this.renderCalendar();
		}
		this.calendar.show();
		this.positionCalendar();
	},

	renderCalendar : function() {
		this.calendar = new YAHOO.widget.Calendar(this.field+'-calendar', this.container, { title:'Choose a date:', close:true, navigator: true } );
		this.calendar.selectEvent.subscribe(this.populateDateField, this, true);
		this.calendar.render();
	},

	positionCalendar : function() {
		var position = YAHOO.util.Dom.getXY(this.field);
		position[1] = position[1] + 25;
		YAHOO.util.Dom.setXY(this.container, position);
	},

	populateDateField : function() {
		var date = this.calendar.getSelectedDates()[0];
		YAHOO.util.Dom.get(this.field).value = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
		this.calendar.hide();
	},

	hide : function() {
		if(this.calendar !== null) {
			this.calendar.hide();
		}
	}

};

The html for creating this widget is as simple as follows:

<script type="text/javascript">
	new DatePicker('date-icon', 'date-field');
</script>
<label>Date: </label>
<input type="text" name="date-field" id="date-field" />
<img src="images/calendar.png" id="date-icon" />

Some benefits to this approach are that the instance of the widget object has direct references to the input id and calendar icon id, and nothing has to be ‘inspected’ at runtime execution of the events. This leads to some cleaner code on a small level. It also has some downsides as we’ll discuss below

Singleton approach

The Singleton approach creates a ’singleton’ wrapper object that creates ONE YUI Calendar widget that is re-used across all input fields. At runtime, the icon clicked on is used to determine which input field is in use through an extra attribute added to the icon image called ‘field’ that contains the id of the input it is linked to. This extra attribute could be avoided by getting the icons previous sibling if it it important to you to validate your html. This code would look as follows:

DatePickerSingleton = {

	calendar : null,

	id : 'date-calendar', 

	container : 'date-calendar-container',

	activeInput : null,

	initialize : function() {
		var icons = YAHOO.util.Selector.query('.date-icon');
		YAHOO.util.Event.addListener(icons, 'click', this.click, this, true);
		this.renderContainer();
	},

	renderContainer : function() {
		var container = document.createElement('div');
		container.id = this.container;
		container.style.display = 'none';
		document.body.appendChild(container);
	},

	click : function(e) {
		this.activeInput = common.byEvent(e).getAttribute('field');
		if(this.calendar === null) {
			this.renderCalendar();
		}
		this.calendar.show();
		this.positionCalendar();
	},

	renderCalendar : function() {
		this.calendar = new YAHOO.widget.Calendar(this.id, this.container, { title:'Choose a date:', close:true, navigator: true } );
		this.calendar.selectEvent.subscribe(this.populateDateField, this, true);
		this.calendar.render();
	},

	positionCalendar : function() {
		var position = YAHOO.util.Dom.getXY(YAHOO.util.Dom.get(this.activeInput));
		position[1] = position[1] + 25;
		YAHOO.util.Dom.setXY(this.container, position);
	},

	populateDateField : function() {
		var date = this.calendar.getSelectedDates()[0];
		YAHOO.util.Dom.get(this.activeInput).value = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
		this.calendar.hide();
	},

	hide : function() {
		if(this.calendar !== null) {
			this.calendar.hide();
		}
	}

};
YAHOO.util.Event.addListener(window, 'load', DatePickerSingleton.initialize, DatePickerSingleton, true);
</pre></div>
The html for creating this widget is as simple as follows:
<div class="code-highlight"><code>
<label>Date: </label>
<input type="text" id="date_field" />
<img src="images/calendar.png" class="date-icon" field="date_field" />

Results

After testing out each of these approaches using a range from 1 to 1000 inputs on a page, I noticed some interesting side effects. Both approaches load using almost the same amount of resources. You might think the Prototype approach would require more memory on page load to create each of the widgets for each input, but in reality, due to the prototype definition, the only additional memory needed for each widget is for the unique element id’s stored as attributes. Each approach also uses a ‘lazy loading’ approach, that causes the Calendar widget to not be created until the user actually clicks on an icon. This is where the two approaches begin to differ.

The Singleton approach consumes a small amount of additional memory on the first click, as it creates the Calendar widget at this time. For subsequent clicks the memory stays the same, as the objects have already been created, and are just being re-used. A downside to this approach is that on page load, a javascript css selector query has to be executed to gather all date picker icons to set up click events for them. This ‘can’ be time consuming with a large number of elements (1000+).

The Prototype approach will consume additional memory for each new icon that is clicked, as there is a Calendar widget created lazily for each input at the runtime click event of the icon. From my simple tests, I saw an increase ranging from 51.2 kb to 358.4 kb for each additional widget instantiated (each new icon clicked). In contrast to the Singleton approach, on page load there is no css selector query to run in order to attach the click events, as the element ids are already in memory from the instantiation of each ‘wrapper’ (DatePicker) object. This saves the possibly heavy css based query, but adds an initialize function for each input to the page load, which can be time consuming as well.

Recently I have been using the Singleton approach for creating widgets where it is possible, as I believe it scales better, and avoids the problem of memory increasing as users go about using the application. This can be accentuated even further when page life cycle is long such as in the case of single page web applications. I found this little exercise interesting in my own work, and hope it is informative for some other people out there. I’d love to hear any comments regarding this from everyone out there.

  • del.icio.us
  • Digg
Tagged , | 6 Comments

slikcalc 1.1 release

I’ve just released a new build of slikcalc – javascript calculator library that includes a few small bug fixes, and some shortcuts to the API. The new API for creating calculators looks as follows:

var columnCalc1 = slikcalc.create('column', {
	total: { id: 'cc-1-total' },
	registerListeners: true,
	calcOnLoad: true
});

as opposed to:

var columnCalc1 = new slikcalc.ColumnCalc({
	total: { id: 'cc-1-total' },
	registerListeners: true,
	calcOnLoad: true
});

Its a small change, but I think is easier to use. Of course the old way will still work, so existing code will not break with the addition to the API. Some other additions include a new fully commented debug version of the code, along with using YUI compressor for the minified version, which shaved off a few kb from previous versions. Full documentation is also included in the download. Take a look and feel free to comment with any feedback.

  • del.icio.us
  • Digg
Tagged , | Leave a comment

Google Chrome – Holy Smokes

The cats out of the bag, Google released their new browser, http://gears.google.com/chrome/. I was pretty excited about the new features that this browser would include, some of which are a brand new Javascript VM called V8, along with using Webkit for the rendering engine. The fact that each tab in the browser is its own process is also awesome news for web developers. I decided to take a run using it to run the web application I develop at my job, which is a large Case Management System by Justice Systems (http://www.justicesystems.com).

I decided to pick a fairly rich page with lots of content and javascript for the benchmark. This page has multiple tabs, and updates a client side data model as the user edits it. As far as page load times go, IE 7 and Firefox 2 were both right around 1.2 – 1.3 seconds just to render this page, and parse the javascript. Chrome comes in at 663 milliseconds, about 50% faster.

The next test I performed was toggling between tabs (YUI tabs). This toggling also involves some front end validation, storing and retrieving of client side data, so I figured it was a pretty good use case for testing out the new Javascript engine. IE 7 comes in at an average of 123 milliseconds to switch tabs, Firefox 2 at 143 milliseconds, and Chrome blows them away at 20 milliseconds.

With Chrome, Google is stating the the browser is a viable platform, which is great news for web developers who have started to see the limitations of current browsers. It makes sense that Google would be the one to push a browser like this, as many of their products are web-based, and rely on a performant browser. I can’t help but think that they have been waiting to see if other browser vendors could provide, but eventually just decided go ahead and get er dun’ themselves. Way to go Google, this is great news for users and developers.

  • del.icio.us
  • Digg
Tagged , | Leave a comment

Teaching an old Framework new tricks!

In summary, I want to discuss an alternative approach for developing a rich, dynamic UI using Struts1. The basic approach is:

  • Java Object to JSON string
  • JSON String consumed by Javascript
  • Manipulate UI, update Javascript model
  • On submit of form serialize Javascript model to JSON string
  • Set value of hidden input to JSON string
  • JSON string to Java Object on server side

Modern web development frameworks have come a long way, in almost every language. Many of the current popular frameworks have integrated widgets or processes for building rich ajax powered UI’s with little hand-rolled code. This makes developing those applications faster and easier. Unfortunately, we can’t always use the latest and greatest new framework as developers.

While working on a J2EE web application that was started over 5 years ago, I’ve learned a lot about how frameworks have evolved since then. When this project was started, Struts 1 was very popular, and a proven framework, so was naturally adopted for the front end. Over time, many things were built to integrate with Struts 1, but provide custom functionality that was required. This makes it very difficult, and highly improbably that a new front end framework can be swapped in due to time and money that would have to be invested. At some point that may be a necessity, but until then, you have to work with what you have.

Building a rich UI using ajax in Struts 1 is … interesting. Sruts1 is very form centric, and all of your form inputs in your UI map directly back to some field on your Java form object in one way or another. This makes it tricky to provide a flexible data structure for a rich UI that may be adding or removing elements. Try adding/removing elements to your page dynamically, and having them map back to your Struts1 Form in a clean way and you’ll see what I’m talking about. A recent approach I took to tackling this situation was to depend very little on the framework.

Lets say I have a Java object graph I want to load into some front end javascript model to work with in the UI. I can fetch this asynchronously as the page loads as a JSON payload, or just dump it to the page into the appropriate place so my javascript consumes it. Either way, I need to make sure its painless to convert this data structure to a JSON string, or create it from a JSON string. This will make passing it back and forth from the server side to the client side much easier.

I can then use this as my front end data model to display, change, remove and add data. When I’m ready to commit my changes, I then have to get that back to my server side Java action. Obviously I could also make the persistence portion asynchronous as well, but sometimes thats problematic, as you may have a lot that goes on in the backend and the rendering of a new page (security, alerts, etc.) that you would have to replicate if you were to do this asynchronously. To keep everything working as normal, one approach is to take your javascript data graph, and serialize it into a json string and set it into an html hidden inputs value. This input can be mapped back to your Struts form, so back in your action, you have a json string you decode and create the appropriate Java objects from. I’ve found this to be a very useful approach when trying to build a very rich UI on top of an older framework. In summary, here are the steps followed:

  • Build your data as Java objects that can be serialized into JSON, and created from a JSON string.
  • Consume the JSON data into your javascript and work with it as needed in the front end.
  • On submit of the form, serialize the Javascript object into a JSON string and set it onto the value of a hidden input
  • Get the value of the hidden input on the server side as your framework supports, and convert the JSON string back to your Java objects
  • Enjoy the praises as everyone is marveled at what you did (actually now days people already expect a rich UI, so you will probably just get to keep your job as the reward)
  • del.icio.us
  • Digg
Tagged , , , | Leave a comment