Archive for February 6th, 2009

I don't like writing function(){$(this).doStuff()} for callbacks and wanted some more elegant way of binding objects to functions. I could always use something like Prototype's bind, but I don't want to modify built-in types (because John Resig says not to) and I generally just want to bind plugins to jQuery objects, so it ought to be a plugin. Inspired by Ariel Flesler's jquery.sugar and John Resig's ultrachaining.

So we have $.later and $.fn.later. $.later() returns a chainable function that is bound at call time to this. $.later().css('color', 'red').append('<span>more</span>') is the same as function() { $(this).css('color', 'red').append('<span>more</span>') }. $(selector, context).later() is similar, but binds to $(selector, context) at call time: $('p').later().css('color', 'red').append('<span>more</span>') is the same as function() { $('p').css('color', 'red').append('<span>more</span>') }

Download the code.

Examples


	$('#example1').click($.later().toggleClass('bold'));
	

	<div id="example1">
		Example 1: 
		<span>Click Me</span>
	</div>
	

	$('#example2').click($('.example:last').later().animate({fontSize: '+=2'}, $('.example:first').later().fadeOut().fadeIn()));
	

	<div id="example2">
		Example 2: 
		<span class="example">Click Me</span> | 
		<span class="example">Watch Me</span>
	</div>