Created
November 28, 2017 16:02
-
-
Save kthalmann/33ebfc1094a6e4fc5af7b356e31f876b 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
class FormHandler { | |
constructor($container) { | |
this.$container = $container; | |
this.$notesContainer = $('.notesContainer'); | |
this.$savingMsgContainer = $('.notesContainer .savingMsgContainer'); | |
this.bind(); | |
} | |
bind() { | |
let that = this; | |
// autosave changes with 1s delay | |
let timeoutId; | |
$('.notesContainer form textarea, .notesContainer form input').on('input propertychange change', function (e) { | |
clearTimeout(timeoutId); | |
timeoutId = setTimeout(function() { | |
that.sendForm(that.$notesContainer.find('form')); | |
}, 1000); | |
}); | |
} | |
sendForm($form) { | |
let that = this; | |
$.ajax({ | |
url: $form.attr('action'), | |
type: 'POST', | |
data: $form.serialize(), | |
beforeSend: function() { | |
that.showSavingMessage() | |
}, | |
success: function (e) { | |
that.hideSavingMessage() | |
}, | |
error: function(xhr, textStatus, errorThrown) { | |
if (process.env.NODE_ENV !== 'production') { | |
console.log(errorThrown); | |
console.log(xhr); | |
} | |
that.showErrorMessage() | |
} | |
}); | |
} | |
showSavingMessage() { | |
this.$savingMsgContainer.append('<span class="label label-default">Saving changes...</span>'); | |
} | |
hideSavingMessage() { | |
this.$savingMsgContainer.empty(); | |
} | |
showErrorMessage() { | |
this.$savingMsgContainer.append('<span class="label label-danger">There was an error while saving changes</span>'); | |
} | |
} | |
export default FormHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment