Skip to content

$.later: binding jQuery plugin methods

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>

{ 5 } Comments

  1. Peter Mounce | February 13, 2009 at 4:26 am | Permalink

    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 | February 13, 2009 at 5:32 am | Permalink

    @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. Peter Mounce | February 13, 2009 at 9:33 am | Permalink

    Ah; gotcha.

  4. Ramin | March 7, 2009 at 12:00 pm | Permalink

    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 :)

  5. Danny | March 7, 2009 at 7:43 pm | Permalink

    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.

Post a Comment

Your email is never published nor shared. Required fields are marked *