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>') }
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>
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!
February 13, 2009, 4:26 amDanny says:
@Peter Mounce:
This is not solving a major problem. It just encapsulates the anonymous function;
instead of using a callback of
use
It’s a matter of taste. I haven’t decided myself whether to use this in real life.
February 13, 2009, 5:32 amPeter Mounce says:
Ah; gotcha.
February 13, 2009, 9:33 amRamin 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 :)
March 7, 2009, 12:00 pmDanny says:
@Ramin:
March 7, 2009, 7:43 pmYeah,
later
isn’t great. I was thinkingdefer
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.Danny