I have a lot of JavaScript/ JQuery code blocks to handle asynchronous data processing in my page. Each code block has three functions (code is incomplete and for illustrative purpose only):
encapsulates $.ajax call:
function doSomething(data){ // do some preprocessing $.ajax({}); // some JQuery Ajax operation that accepts data // do some postprocessing return false; }
handles the response:
function handleResponse(result){ // process the result return false; }
handles any error:
function handleError(XMLHttpRequest, textStatus, errorThrown){ // gracefully handle the Error and present relevant information to user return false; }
In a page that requires a lot of data processing I end up having a lot of these blocks which seems to be duplication so I decided to do some refactoring.
I figure there would be different ways to go about this.
- One could have one error handler that can be reused across Ajax calls (obvious).
- One could maybe reuse some response handlers but this would be akward as responses are very different depending on call.
- Maybe create some kind of prototype object that provides base functionality and have a static method for error handling (can this be done in JavaScript?).
Just wondering if anyone has come across this and/or if there is a best practise solution for this?
Thanks!