Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery design pattern for selectors to improve code maintainability?

Yesterday I had to go back to a page I had worked on a few weeks ago to redo the UI. The UI consisted of a jQuery UI tab control with 3 tabs. Each tab had 3-5 controls inside of it, and a submit button to only submit the data within the tab. I had to reorganize some of the tabs, remove some textboxes, add some drop down lists, modify some behaviors and even work a bit on the client side validation (which uses jQuery Validation). What I found during this excercise, thought, was that I had to go back and recheck each and every one of my jQuery selectors. Some were left intact, but many of them changed.

I'm wondering what design pattern (if any) do people use to avoid or minimize the effect of refactoring or reworking a webpage that had heavy jQuery usage. I'm sure it can't be just "Search" + "Search And Replace".

like image 341
enriquein Avatar asked Jul 06 '11 12:07

enriquein


2 Answers

It's in general a very good idea to store node references commonly used. This could be done in some kind of "init script file" or in each "module" if you have modules separated by files.

For instance

var myNamespace = window.myNamespace || { };

$(document).ready(function() {
    myNamespace.nodes = {
        header:   $('#header'),
        content:  $('#overlay > .content'),
        footer:   $('#footer')
    };
});

somewhere else in your code you should only access elements over such a hash lookup. Later if selectors change, you only need to replace / modify the selector strings in one place and all the rest keeps working.

// somefile.js
var myNamespace = window.myNamespace || { },
    myNodes = myNamespace.nodes;

$(document).ready(function() {
    if( myNodes ) {
        myNodes.content.animate({ top: '+=200px' }, 1000);
    }
    else {
        throw new Error('Arrrrrrr the <center> cannot hold! it is too late');
    }
});

That concept also provides a better performance for your whole webapp. By quering nodes only once, since this is still a pretty expensive DOM operation.

like image 185
jAndy Avatar answered Nov 14 '22 03:11

jAndy


I think of this list:

  1. Having no track of HTML elements in your selectors, because if you show your message in a paragraph today, maybe you want to show it in an span tomorrow.
  2. Use semantic Id and classes. (semantic naming and IDs prevents from future changes to those names, thus less selector changes)
  3. Use multiple classes, not just one long descriptive class. (something like tagging. Instead of having error-message class, have error message classes)
  4. Use less traversing, that is, going from child to parent and from this node to previous, or siblings and stuff. (it's directly related to nesting levels).
like image 2
Saeed Neamati Avatar answered Nov 14 '22 03:11

Saeed Neamati