Search code examples
jqueryrefactoringmaintainability

jQuery Refactoring/Maintaining


I've searched a little bit around SO and haven't found any questions/answers that are helping me. The problem is my jQuery function calls are getting much too large to maintain. I'm wondering if I should be refactoring a lot more or if there is a better way to do all of these calls. You'll see as I make one call, the anonymous functions that are arguments for the function end up being very large and make the readability of the code terrible. I could in theory break all these up into their own functions but I don't know if that's a best practice or not. Here is an example of some of the jQuery so far:

$('#dialog').html('A TON OF HTML TO BUILD A FORM').dialog('option', 'buttons', { 'Save': function(){$.post('/use/add/', $('#use_form').serialize(), function(data){ ......There were 4 more lines of this but I'm saving you so you don't rip your eyeballs out hopefully you get the idea.....dialog('option','title','New Use').dialog('open');

As you can see since so many of the functions I'm calling take functions as arguments, when I create anonymous functions I end up with a huge mess (there were about 3 more anonymous function declarations in this code)

Should I simply make a bunch of functions and call those to make it more readable. The only reason I'd be against this is because I'd have a bunch of functions declared that are only used once.

Thanks in advance for the help!


Solution

  • Define the functions in the correct scope and it's not a big deal.

    var generateHTML = function() {
      ...
    };
    var somethingElse = function() {
      ...
    };
    
    ... some more ...
    
    $('#dialog').html( generateHTML() )...etc
    

    There's not much else you can do except reorganize your code in general (say, using an object oriented style) to encapsulate code so it isn't so messy.