If you're using Javascript functions to populate HTML tables, etc., and you find you have a lot of HTML mixed with your code, stop!

Encapsulation is the process of separating out functions within your code, but also describes separating the function of your code from a the form (or design) of your page. Instead of embedding the HTML in your function calls, export the data that you need from your function as an object, and then use simple control loop to iterate through that object and populate your page within the HTML.

eg:

<%

function blahBlah(myInput) {

for (i=0; i<3000; i++) {

myname = <result of series of operations>;

myurl = <result of a series of operations>;

myObject[i] = {name:name, url:url};

}

return myObject;

}

%>

Then in your HTML, you just need the following, regardless of the complexity of the previous functions:

<table>

<tr>

<td>page name</td>

<td>link</td>

</tr>

<%

var myObject = blahBlah(someInput); var ol = myObject.length;

for (i=0; i<ol ; i++) {

%>

<tr>

<td><% = myObject[i].name %></td>

<td><a href="<% = myObject[i].url %>">link</a></td>

</tr>

<%

}

%>

</table>

Some good things about this method:

  1. You can totally separate your code from your HTML, allowing designers to change the HTML without giving you a heart-attack.
  2. The complexity of your function to populate the object can be hideous without you needing to worry about fitting it to the design.
  3. Because your enumerators (like the variable i) are stored at function level, there's no problem with scope.
  4. The function is totally reuseable within other HTML pages that have a different design without requiring a rewrite.
  5. Dreamweaver won't choke on your code and mangle it.
  6. Makes debugging incredibly easier.