James' Website

March 18, 2006

Chaining Functions in JavaScript

It's just a tiny pattern, but I see it done wrong all over the place. It's needed when you want to drop a reusable block of code into a page and the code must respond to browser events. If you assign a function member to window.onload like this:

function handler(){
	alert('IronPython is going to seriously kick ass.');
}
window.onload = handler;

You'll overwrite any other functions that may have been assigned to that handler. Instead, use this function to join them together:

function appendFunction(fnA, fnB){
	return	(fnA && fnB) ? function(){return fnA() && fnB();}:
		fnA ? function(){return fnA();}:
		fnB ? function(){return fnB();};
	};
}

This is a simple higher order function. It takes in two functions A and B and returns one new function that calls both of them (or less than both, if A and/or B are undefined.) Both functions get fired when the event happens, and both have a chance to cancel something by returning false.

var fnCheckForm = function(){ return chkAccept.checked; };
form1.onsubmit = appendFunction(form1.onsubmit,fnCheckForm);
...
var fnCheckFormAgain = function(){ return window.confirm('ok?'); };
form1.onsubmit = appendFunction(form1.onsubmit,fnCheckFormAgain);
...
Add a Comment