Sacrificial Lambda
read 7 commentsDynamically 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.















Hey Dan,
So, a "lambda function" is the same thing as an anonymous function, right?
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!
You could take this one step further and make it as DRY (Do not Repeat Yourself) as possible:
I hope that code is readable...
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.
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?
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.
Sientz :
You could set an id to a div wrapping the "containers" and simplify the hide_function and even integrate the hide and show_function by sending the object the you want to display in the funcion_calling.
I'm sure this can be optimized