-
-
Save anderson-mota/6222813 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This Class serializeTo | |
* Return dataserialize object, array or string | |
* @author Gustavo da Silva Rodrigues <[email protected]> | |
*/ | |
;(function ( $, window, document, undefined ) { | |
var pluginName = "serializeTo", | |
/** | |
* default Configuration | |
* @param Object defaults | |
**/ | |
defaults = { | |
/** | |
* Config | |
* @parm Object | Array | String returnType | |
**/ | |
returnType: {}, // {}, [], '' | |
}; | |
function Plugin ( element, options) { | |
this.element = element; | |
this.settings = $.extend( {}, defaults, options ); | |
this.dataArray = $serilizeData = $(document).find(this.element).serializeArray(); | |
this._defaults = this.settings || defaults; | |
this._name = pluginName; | |
this.result = {}; | |
this.init(); | |
return { | |
result: this.result | |
} | |
} | |
Plugin.prototype = { | |
init: function () { | |
var _this = this; | |
switch (Object.prototype.toString.call( this._defaults.returnType )){ | |
case '[object object]' : | |
for(var data in this.dataArray){ | |
this.result[this.dataArray[data].name] = this.dataArray[data].value; | |
} | |
break; | |
case '[object Array]' : | |
this.result = []; | |
for(var data in this.dataArray){ | |
this.result[this.dataArray[data].name] = this.dataArray[data].value; | |
} | |
break; | |
case '[object String]' : | |
this.result = ''; | |
for(var data in this.dataArray){ | |
this.result += this.dataArray[data].name +' : '+ this.dataArray[data].value +'\n'; | |
} | |
break; | |
default: | |
this.result = {}; | |
for(var data in this.dataArray){ | |
this.result[this.dataArray[data].name] = this.dataArray[data].value; | |
} | |
break; | |
} | |
return _this; | |
}, | |
}; | |
$.fn[ pluginName ] = function ( options, callback ) { | |
if (typeof callback == 'function') { // make sure the callback is a function | |
callback($.data( this, "plugin_" + pluginName, new Plugin( this, options ))); // brings the scope to the callback | |
} else { | |
return $.data( this, "plugin_" + pluginName, new Plugin( this, options )); | |
} | |
}; | |
})( jQuery, window, document ); | |
$('#teste').on('submit', function(e){ | |
e.preventDefault(); | |
var x = 0 | |
//to string mode | |
console.log($('#teste').serializeTo({returnType: ''})); | |
//default | |
console.log($('#teste').serializeTo()); | |
//callback function | |
$('#teste').serializeTo({returnType: []}, function(x){ | |
console.log(x); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment