Sacrificial Lambda
Dynamically binding event handlers to content that has been ajaxed in with $.load without repeating yourself can be tricky. Lambda functions help you to not repeat yourself as much. jQuery uses lamdba functions everywhere, so if you're familiar with jQuery, you should be familiar with the syntax of lambda functions.
In this example, the ajaxed-in content contains the elements that trigger a $.load over themselves.
-
prepare_links = function() {
-
return false;
-
});
-
return false;
-
});
-
};
-
prepare_links();
-
});
Make sure you're not calling the function in the callback by accidentally using prepare_links():
This would set the callback to whatever the return value of the function is, not to the function itself.



September 3rd, 2006 at 2:07 pm
Hey Dan,
So, a "lambda function" is the same thing as an anonymous function, right?
September 3rd, 2006 at 4:03 pm
Thanks, I finally stumbled across this technique when I got sick of wrapping all the functions I wanted to run in $('document').ready() with function(){} wrappers. This way is much cleaner, it's nice to see that I'm on the right track with that.
The recursion in prepare_links is also something new to me; I didn't realize that you could self-refer to a function definition in this way. Neat. Confusing, but neat.
PS this blog is a great idea!
September 3rd, 2006 at 4:37 pm
You could take this one step further and make it as DRY (Do not Repeat Yourself) as possible:
I hope that code is readable...
September 4th, 2006 at 3:53 am
Oops, it can be written even DRYer:
do_load = function() {
$(’#calendar’).load(this.href, prepare_links);
return false;
}
prepare_links = function() {
$(’.previous-month, .next-month’).click(do_load);
}
$(prepare_links);
Heh.
April 13th, 2007 at 9:57 am
You have forgoten next moment. To set the whole construction callback to null. Your example overflows browser buffer.
prepare_links = function() {
prepare_links = false; ///!forgoten
So, what do you thing about it?
February 21st, 2008 at 2:22 am
Do I need to use that =false somewhere in my script? I have created a div_switch function that hides all my functions at the bottom, where would I insert the div_switch = false; if needed??
If there is an easier way to do this, please feel free to educate me, I am a rookie at this scripting stuff.