Scoping Javascript closures in loops

It must have been something I ate, cause this is like the third post in 2 days I think! This is a quick one, but super handy to know if you don’t already. There is semi-common problem I run into, and it has to do with scoping of closures inside of loops. Lets get straight to the code so its easier to understand what I’m talking about:

<html>
<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/utilities/utilities.js" ></script>
<script type="text/javascript">
	var values = [0,1,2,3,4,5,6,7,8,9];
	for(var idx in values) {
		//First Test - will have incorrent scoping
		YAHOO.util.Event.addListener(window, 'load', function() {
			YAHOO.util.Dom.get('wrong-scope').innerHTML += ' '+values[idx]+' ';
		});
		//Second Test - scoping will be correct
		YAHOO.util.Event.addListener(window, 'load', function(scopedValue) {
			return function() {
				YAHOO.util.Dom.get('right-scope').innerHTML += ' '+scopedValue+' ';
			}
		}(values[idx]));
	}
</script>
<body>
<div id="wrong-scope">
<h1>Wrong Scope</h1>
</div>
<div id="right-scope">
<h1>Right Scope</h1>
</div>
</body>
</html>

In this example, there is a simple array of ordered values, and then a loop over those values. For each iteration of the loop, there is an onload listener added that will dump that value into a div. You’ll see the first loop always dumps 9, because the scoping is wrong when the closure executes, and the last time through the loop sets the scope of values[idx].

The second section does some unique handy-work to correct the scoping. A listener is added like before, but the closure is created in a specific fashion in order to get the scope to be the way we want at runtime. For the closure in the second section, we create a function, and immediately execute that function, passing in a parameter that is the current value in our array of numbers. That function runs, and returns another function that does the appending to the div of the value. This second, inner-function is what will execute on page load. Because of the outer-function we immediately called, the variable passed into it, the current value from our array, will be available, and properly scoped for our inner-function.

scoping

This is a handy trick when you have a situation where you are looping over a collection, and are providing some type of callback/closure for each entry, but need some proper scoping.

  • del.icio.us
  • Digg
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
Tagged , , | 1 Comment

Browser autocomplete and keyup events

Browser oddities are nothing new, but I came across one today that I haven’t heard about before, and couldn’t seem to find many comments about on the interwebs. To get to the gist of it, when the native browser autocomplete functionality pops up for a text input, it also triggers a keyup event for the input. I had some logic going on where I was firing an ajax lookup request as a user types in a value, and was waiting for a delay in their typing to fire the ajax request. I noticed I would often get two events fired at almost the same time. At first I chalked it up to oddities with setTimeout() not being completely accurate, but with more investigation, the native autocomplete that the browser supplies was the culprit.

To try this for yourself, here is the test code I was using:

<html>
	<script type="text/javascript">
		function handleEvent() {
			document.getElementById('keyup-test').innerHTML += document.getElementById('test').value + '<br />';
		}
	</script>
<body>
	<form action="">
	<div id="keyup-test"><h1>Test Keyup Event</h1></div>
	<input type="text" id="test" onkeypress="handleEvent();" value="bradharris" />
	</form>
</body>
</html>

You’ll see the current value of the input written out into a div above the input on each keyup event. To get the autocomplete functionality of the browser working, just type in a value, and then submit the page by pressing enter when the input is focused. The browser will then have that entry in its history of values for that input, and will start firing the keyup an extra time when it finds a match and shows the autocomplete box. To turn it off, just add autocomplete=”off” to the input tag, then it should only fire once per keyup. I’m pretty perplexed as to why this exists, and I’ve seen it in IE7 and Firefox3 (Linux and Windows). If anyone knows why its around, I’d love to hear.

  • del.icio.us
  • Digg
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
Tagged | 3 Comments

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
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
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
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
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
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
Tagged , | Leave a comment

Page optimized by WP Minify WordPress Plugin