Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Simple idea: just have a plugin (more a basic function). That I can use with jQuery in different ways it offers, means:

var myNewVar = $.myNewFunction( myVar );
var myNewVar = $().myNewFunction( myVar );

I want to know if what I did is the good way to doesn't repeat the code, or if their is a better way to.

Here my plugin:

// New function to jquery to change an array (from form) to an object
$.formArrayToObject = function( array ) {
    var form = {};
    $(array).each(function(){
        if( !form[this.name] ) {
            form[this.name] = this.value;
        }
        else {
            if ( !Array.isArray(form[this.name]) ) {
                form[this.name] = [form[this.name]];
            }
            form[this.name].push(this.value);
        }
    });
    return form;
};

// Second declaration to be able to call both $. and $().
jQuery.fn.formArrayToObject = function() {
    $.formArrayToObject();
};
share|improve this question
    
And I'm open to any other suggestion about my code if there is –  Anc Ainu Apr 18 '14 at 9:49

1 Answer 1

up vote 4 down vote accepted

Since your function - as far as I can tell - doesn't rely on a jQuery collection, I'd stick to always using "1 true way" of calling it.
I.e. I assume that

$("some > selector").formArrayToObject(arr) === $.formArrayToObject(arr);

that is, the two ways of calling it give the same exact result.

If that's the case, just use $.yourFunction and only that. Having two invocations that should be semantically different but actually aren't is just confusing.

For instance, jQuery doesn't have both $.ajax() and $(...).ajax() simply because the latter doesn't really make sense; the $.ajax function isn't dependent on a certain context or selector, so why would you call it as if it was?

(besides, your second declaration in the code above is broken; it ignores arguments)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.