views:

56

answers:

3

I am in the process of writing a small javascript library to make form creation/validation easier. This is mostly an excuse to get better with javascript. I am debating about how to take in user input for form element creation.

I am looking at two approaches. One is to take in a few pre-determined parameters such as id, label, value

The other is to take in a single object which will be used to write properties straight into the form element. So for example if I wanted to pass in id label and value, I would simply pass in {id : 'my_id', label : 'my_label', value : 'my_value}

The third option is to take in id, label, options where options is an object which does what I have described above.

Right now the passing an object in seems the most flexible, but I wonder if there are any serious downsides to this? I would like this to be easy to use for most javascript users. Any thoughts on the best way to do this?

+1  A: 

The usual way of handling this is with an options object as in your second choice. Most plugins (and jQuery methods) that require options use that pattern. As far as I'm aware there are no downsides to this and as its a very common way of handling options, I don not see it being hard to use for others.

Option 3, is also acceptable if you have something that absolutely must be passed in eg. id. Just in that case the options object is most commonly found as the final parameter of the function.

Hope this helps

Darko Z
A: 

You can support both, with a bit of hackery. You can inspect the all the arguments passed to the function:

You can then use a condition like :

var func = function(){
    if(arguments[0].id) {
        id = arguments[0].id;
    } else {
        id = arguments[0];
    }

    // .. and so on ...
}

This basically says that if the first argument is an object, extract the id, else use the argument directly.

I prefer the object way, it lends itself to be used by external JSON data sources.

sandesh247
+1  A: 

Using objects seems to be the "standard" way to do that in the JS code that I've studied.

Using a list of specific parameters, which adds an ordering requirement, quickly gets out of hand when you have more than a few parameters.

If you have a "dependent" parameters, e.g., ones that only appear for certain values of another parameter, then that's especially ugly when using a simple parameter list.

Be careful when iterating over the properties of an object, however. It's easy to get inherited elements that aren't intended. Douglas Crockford recommends using hasOwnProperty() to check for this case.

Tim Sylvester