views:

136

answers:

2

I'm writing a plugin that will allow parameters to 'set it up.' But I predict the user won't always want to set up every aspect of the function.

function This_Function(a,b,c,d);

For instance, maybe they'll only want to set up a and c, but not b and d (they'll just prefer to leave those as defaults). How do I write the function (or the parameters for that matter) so that the user can customize which functions they would prefer to pass? I have a feeling it involves parsing input, but I've seen many other functions with this capability.

Thanks in advance for the help.

+5  A: 
function This_Function(options){
    // set up the defaults;
    var settings = {
        'opt1':2,
        'opt2': 'foobar'
    };
    $.extend(settings,options);
    if (settings.opt1 > 10) {
        //do stuff
    }
}

Will let you users do something like this:

This_Function();
This_Function({'opt1':30});
This_Function({'opt2':'jquery'});
This_Function({'opt1':20,'opt2':'javascript'});
PetersenDidIt
If you're using JQuery, this is the way to do it.
Plynx
Figured if they added the jQuery tag they were using jQuery
PetersenDidIt
This is exactly what I was looking for. You're a saint, Plynx.
dclowd9901
+1  A: 

A more transparent way...

function This_Function(options) {
    var a = options.a;
    var b = options.b;
    var c = options.c;
    var d = options.d;
}

This_Function({a:12; c:'hello'; d:1);

plodder
This is great, too. Thanks. I gave you +1.
dclowd9901