I have written a plugin with the following “signature”:
jQuery.fn.attach = function(element, settings, duration, options, callback) {
Here element is a jQuery object, settings are my custom settings for my plugin and duration, options and callback are all parameters that I use in jQuery’s animate, like this:
someObject.animate({ someCSS }, duration, options, callback);
Now, my question is: Is it possible to make this function easier to call? For instance, right now, to get everything to work as I expect… I have to include all parameters and set the parameters that I don’t use to null:
$(this).attach($('#e1-blue'), null, 3000, null, function() { alert('done'); });
It would be nice to also be able to call this as:
$(this).attach($('#e1-blue'), 3000, function() { alert('done'); });
and as this (ofc)…
$(this).attach($('#e1-blue'), 3000);
Any suggestions?
The simplest thing I can think of is re-ordering the parameters such that the most commonly used ones come first. So if you change the function to:
then you can make everything (except probably the first parameter) optional by putting default values into the function body. Such as:
Then
and
would both be valid, with the other values automatically populated with
null.Strictly speaking, you could check for parameter types inside the function e.g. if the second paramter is an integer then it’s the
duration, if it’s a function it’scallback, if it’s an object it’ssettings, but I don’t think people who have to follow your code later will thank you for it. It could also make the function difficult to extend later down the line if e.g. a second integer parameter was required.