1
\$\begingroup\$

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();
};
asked Apr 18, 2014 at 9:43
\$\endgroup\$
1
  • \$\begingroup\$ And I'm open to any other suggestion about my code if there is \$\endgroup\$ Commented Apr 18, 2014 at 9:49

1 Answer 1

4
\$\begingroup\$

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)

answered Apr 18, 2014 at 11:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.