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.



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

	$('#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>


  1. Peter Mounce says:

    I don’t get it. Can you spell out the problem this solves? It seems like I should be grokking it, but the mental leap (probably a hop…) is escaping me.

    It seems like both ways use an anonymous function…? I’m clearly missing the point!

  2. Danny says:

    @Peter Mounce:
    This is not solving a major problem. It just encapsulates the anonymous function;
    instead of using a callback of




    It’s a matter of taste. I haven’t decided myself whether to use this in real life.

  3. Ramin says:

    typing out function() {} every time for an anonymous function is kind of annoying. But I think the word “later” is a bit confusing as well. Maybe use a symbol instead? Like how jQuery uses $ … maybe another symbol to represent anonymous functions? That would be cool :)

  4. Danny says:

    Yeah, later isn’t great. I was thinking defer might be better, which I think Prototype uses. Javascript 2 is supposed to have some syntactic sugar to make anonymous functions/code blocks more palatable, but for now we’ve got to stick to real Javascript. I think a symbol would be too confusing.

Leave a Reply

Warning: Undefined variable $user_ID in /home/public/blog/wp-content/themes/evanescence/comments.php on line 75