Last active
October 24, 2016 05:14
-
-
Save acarbonaro/7a96c8af267e9b15a9ac1d451945651c to your computer and use it in GitHub Desktop.
Socket.IO Autoform
This file contains hidden or 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
| ;"use strict"; | |
| /*** | |
| * Transform normal ol' HTML forms into magical socket-abusing creatures | |
| * @param [forms] An array of HTML forms | |
| * @param socket The socket to use | |
| */ | |
| function autoform (forms, socket) { | |
| let formsLength = forms.length; | |
| for (let i = 0; i < formsLength; i++) { | |
| let form = forms[i]; | |
| form.addEventListener("submit", function(e) { | |
| e.preventDefault(); | |
| let errors = []; | |
| // Get the key names without duplication; this is most definitely a hacky thing to do. | |
| let formKeys = Object.getOwnPropertyNames(this.elements).slice(-(this.elements.length)); | |
| // Loop through the array keys, pulling out the key name and value. | |
| let formArray = formKeys.map(function(key) { | |
| let element = this.elements[key]; | |
| // TODO: check for errors here, maybe | |
| return { [key] : element.value }; | |
| }, this); | |
| // Remove the submit button from the data. | |
| formArray.splice(formArray.indexOf("submit")); | |
| // Merge the data into a single object. | |
| let formData = formArray.reduce(function(resultData, incomingDatum) { | |
| for (let key in incomingDatum) { | |
| resultData[key] = incomingDatum[key]; | |
| } | |
| return resultData; | |
| }, {}); | |
| // Extract the form action | |
| let formAction = form.action.substring(form.action.lastIndexOf("/") + 1, form.action.length); | |
| if (errors.length) { | |
| errors.forEach(function (error) { | |
| log(error); | |
| }); | |
| } | |
| else { | |
| // Send the data in a socket | |
| socket.emit(formAction, formData); | |
| this.reset(); | |
| } | |
| }, {}); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment