Disclaimers:
- I’m still learning my way with jQuery.
- Code here is pseudocode carved from functioning code (and even then only partly so), so it’s untested in real world.
I was curious as to how jQuery does parameter expansion in event handlers with callbacks. Googling I could only come up with resources that would call their custom functions with parameters given as object literals, like so:
myFunc({
parameter1 : 12345,
parameter2 : "foo"
});
, which, when using a callback parameter, would go something like:
myFunc({
parameter1 : 12345,
callback : function() {
return true;
}
});
Now, there’s nothing wrong with that as such. What I wanted however, was to be able to call my custom functions in the elegant way jQuery does it, without the object literal brackets surrounding the parameters, like so:
myFunc(12345, function() {
return true;
});
Here’s how I could achieve this:
jQuery.fn.myFunc = function() {
var options = {
parameter1 : (arguments[0] || 0),
callback : (arguments[1] || function() { return false; })
}
do_stuff_with_param1(options.parameter1);
return options.callback();
}