Breaking Prototype habits in a jQuery world

Jqueryinaction
When you get used to doing things one way, it's hard to retrain yourself. It took me months to "get" the Prototype way of doing things after a decade of writing all of my own Plain Old JavaScript, sans framework. Now that I'm more likely to use jQuery, I've still got some residual Prototype habits to break.

In Prototype's Enumerable class, you call the each method to iterate over a collection. In jQuery, you can do the same - but you often don't have to. Many of the standard jQuery methods automatically iterate over the member nodes of a jQuery object. There's usually no need to do so manually using jQuery's version of each. My friend and former colleague Zack Frazier reminded me of this fact the other day, in response to this original post. His input helped me fine-tune my JavaScript on the new Pathfinder website.

Compare my original version of this code, which transforms target="_blank" windows into more finely controlled JavaScript popups:

/*manage the windows spawned by offsite links*/$('a.offsite').each(function() {	var link = $(this);	var width = (		link.hasClass('blogLink') ||		link.hasClass('moreBlog')	) ? 1050 : 750;	var url = link.attr('href');	$(link).click(function() {		var win = window.open(url, '_blank', 'width=' + width +		',height=550,menubar,resizable,status,location,toolbar,scrollbars');		if (win && win.focus) {			win.focus();			return false;		} else {			win = null			return true;		}	});});

... to this new, more elegant version:

/*manage the windows spawned by offsite links*/$('a.offsite,a.offsiteWide').click(function() {	var link = $(this);	var width = link.hasClass('offsiteWide') ? 1050 : 800;	var url = link.attr('href');	var win = window.open(url, '_blank', 'width='		+ width		+ ',height=550,menubar,resizable,status,location,toolbar,scrollbars')	;	if (win && win.focus) {		win.focus();		return false;	} else {		win = null;		return true;	}});

As you can see, in a function like this, there's no need for the each method. You can set up necessary variables within the event handler itself, so you can rely on jQuery's click method itself to iterate in place of each.

Contrast this with the other code from my original post: a routine to make navigational menus more friendly by applying click and hover handlers to block-level containers rather than just the links inside those containers. The old version looked like this:

//collect some list items and cycle through them$('ul.icons li').each(function() {

	//apply the url from the link inside the li to the entire li	$(this).click(function() {		document.location.href =			$(this).contents('a').eq(0).attr("href")		;	})	.hover(		//restyle the entire li on mouseover		function() {			$(this).attr('class','hover');		},		//go back to normal on mouseout		function() {			$(this).removeAttr('class');		}	);});

I easily could have changed this to avoid the each iterator, like so:

/*make an entire block-level element clickable*/$('ul.icons li').click(function() {	document.location.href =		$(this).contents('a').eq(0).attr("href")	;}).hover(	//restyle the entire li on mouseover	function() {		$(this).attr('class','hover');	},	//go back to normal on mouseout	function() {		$(this).removeAttr('class');	});

However, my requirements changed a bit. I realized that I wanted to apply this behavior to navigational menus in which the current page was not linked. My revised code therefore had to do some due dilligence before attempting to create its click and hover behaviors. The most elegant way accomplish this was my old friend each. The revised code looks like this:

/*make an entire block-level element clickable*/$('ul.icons li,ul.sidebarNav li').each(function() {	var href = $(this).contents('a').eq(0).attr("href");	if (href) {		$(this).click(function() {			document.location.href = href;		})		.hover(			function() {				$(this).addClass('hover');			},			function() {				$(this).removeClass('hover');			}		);	}});

Sure, I still could have avoided the each iterator:

/*make an entire block-level element clickable*/$('ul.icons li,ul.sidebarNav li').click(function() {	var href = $(this).contents('a').eq(0).attr("href"));	if (href) {		document.location.href = href;	}}).hover(	function() {		$(this).addClass('hover');	},	function() {		$(this).removeClass('hover');	});

But that would have been stupid. I'd have been applying a click element to every single item in my menu, regardless of whether that click event was actually necessary. Not a big deal, but why attach useless events that aren't going to earn their keep?

The take-home is that jQuery's each iterator, while usually superfluous, is helpful when you need to test some conditions before chaining some methods onto a set of elements. Not a profound insight - but one that takes some getting used to if you come from the Prototype world.

Related Services:
Ajax Rich Internet Applications, Custom Software Development

Related posts:

  1. Pathfinder website relaunch: Simple tools for simple problems
  2. jQuery vs. Prototype: OO JavaScript with or without training wheels
  3. Pimp my jQuery: Five plugins to replace the features Prototype and Scriptaculous users expect
  4. Project Website Part 4: Drag and Drop in jQuery
  5. jQuery UI in action: Thumbs up on tabs, thumbs sideways on themes

Comments: 3 so far

  1. as of jQuery 1.2 you can rewrite the last part of the last example this way:

    .hover(
    function() {
    $(this).toggleClass(’hover’);
    }
    );

    All of your other examples still have a lot to polish.

    Comment by rimmer333, Thursday, April 3, 2008 @ 6:47 am

  2. I believe jQuery can avoid the use of “each” because its selector method, $(),
    returns an instance of the jQuery object that has the mentioned method, “click”,
    and others attached.

    In Prototype the selector method, $$(), returns an array.
    You can then use the ‘invoke’ method to call a method of each of its items.

    $$(’a.offsite, a.offsiteWide’).invoke(’observe’, ‘click’, function(){
    var width = this.hasClassName(’offsiteWide’) ? 1050 : 800;
    …..

    At first glance this may seem unnecessarily verbose but the real power comes in
    not being limited to the methods attached to the array (or the jQuery object).

    For example on an array of strings I can call ‘truncate’:
    arrStrings = arrStrings.invoke(’truncate’, 10);

    Or on an array of dev defined objects:
    var calculations = arrCalcs.invoke(‘doComplexCalculations’, arg1, arg2);

    It’s chainable as well:
    $$(’#windows div.close’).invoke(’addClassName’, ‘active’).invoke(’show’);

    Your “take-home” can be applied to Prototype as well.
    Great article, just though I should clarify some of the prototype info. :)

    -JDD

    Comment by jdalton, Thursday, April 3, 2008 @ 10:41 am

  3. @rimmer333: I don’t think that works. I’m using 1.2.3 and hover needs 2 arguments: one function each for the mouseover and mouseout states.

    @jdalton: Totally agreed with your analysis. I think both libraries offer pretty similar functionality but differ in the way they trade off elegance and power.

    Comment by Brian Dillard, Monday, April 7, 2008 @ 1:56 pm

Leave a comment

Powered by WP Hashcash

Launch: Pathfinder Newsletter

    Get a monthly update on best practices for delivering successful software.

    Subscribe via email


    Subscribe via RSS      RSS icon

Topics

Search

WordPress

Comments about this site: info@pathf.com