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();
};
-
\$\begingroup\$ And I'm open to any other suggestion about my code if there is \$\endgroup\$Tancrede Chazallet– Tancrede Chazallet2014年04月18日 09:49:41 +00:00Commented Apr 18, 2014 at 9:49
1 Answer 1
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)