09 June, 2011

jquery.defaults.js

JavaScript doesn't let you define default values for arguments of functions, which, considering their heavy use throughout the language, can be quite a pain.
In addition, a very common pattern is to use one of the arguments of the function as a collection of name:value options and to add an object with their default values inside the function's scope. However repeating the same code every time is not that nice and adding it to external functions requires even more work.

My new jQuery extension jquery.defaults.js to the rescue!
It adds two functions to jQuery, defaults and options. They both return a wrapper around their first argument, with defaults setting default values for the arguments' list and options implementing the pattern described above.

Examples:
var f1 = $.defaults(f, [1, undefined, "3"]);//using an array of default values

or

var f1 = $.defaults(f, {"0":1, 2: "3"});//the same using an object with the argument positions as keys

Calling f1() will pass (1, undefined, "3") while calling f1("a", 2) will pass ("a", 2, "3").

var f2 = $.options(f, {key:"value", a:"a"});//the position of the options argument is 0 by default
var f3 = $.options(f, 2, {key1: "value1"});//but it can be explicitly declared as the 2nd argument

Calling f2({a:"b"}) will pass ({a:"b", key:"value"}), while calling f3(1) will pass (1, undefined, {key1: "value1"}).

The functions resulting from applying the two can be mixed and chained together as much as necessary for even cooler effects.

Grab the code from my GitHub project bits.and.pieces.js and check the unit tests in the test folder for more examples. There is also a minified version if you feel like using it in production.