Snippet: jQuery Refresh

June 27, 2009

A big problem I always come across when manipulating the DOM, is the fact that events you've attached on a global scale don't attach to the new group of objects added from ajax requests and the like.

I know that jQuery has a fix for this with the live function. But it's limited in what type of events you can attach with it.

In the midst of this problem, I wrote a small extension to the jQuery object, that may be of use to some of you out there. It's called refresh:

/**
 * jQuery Refresh
 * June 27, 2009
 * Corey Hart @ http://www.codenothing.com
 *
 * @function o: Pushes enclosed function onto the stack
 * @object o: Loops through the stack and passes the context supplied
 */ 
jQuery.extend({
	// Initialize the stack
	refreshStack: [],

	// Refresh functionality
	refresh: function(o){
		if ( jQuery.isFunction(o) ){
			jQuery.refreshStack.push(o);
		}else{
			if ( typeof o !== 'object' ) o = document;
			for ( i in jQuery.refreshStack ) jQuery.refreshStack[i](o);
		}
	},
});

It works by storing a supplied set of functions, and running them when asked. Below you have two seperate forms that contain a list of checkboxes. The first form latches the checkall function only after the DOM is ready. The second uses the refresh method above. Press the Check All buttons on each of them to see how they work.

Check All
Box 1
Box 2
Box 3
Box 4
Box 5
Check All
Box 1
Box 2
Box 3
Box 4
Box 5
Reload Forms

As you can see, refresh reattaches the checkall functionality to the newly loaded form. To limit processing time, you can pass the context of the form to the refresh function. Here's the example of the form above:

$(document).ready(function(){
	// Form 1
	$('#form1 .ctrl').click(function(){
		$('#form1 input[type=checkbox]').attr('checked', $(this).is(':checked'));
	});

	//Form 2
	$.refresh(function(context){
		$('.ctrl', context).click(function(){
			$('input[type=checkbox]', context).attr('checked', $(this).is(':checked'));
		});
	});
	// Run the stored function
	var $obj = $('#form2');
	$.refresh($obj);
});

// Reload the forms when clicking the reload link
function reloadForms(){
	$('#form1').load('/ajax.php?ajax=blog-examples&blog=17');
	$('#form2').load('/ajax.php?ajax=blog-examples&blog=17', function(){
		$.refresh(this);
	});
}
Have a question or comment? ask@codenothing.com.