Using Teamworks code to write JavaScript

Here’s a little trick I learned recently and might be of use to someone else out there.

The basic requirement is to dynamically change the options in a combo box, based on data held in teamworks variables. More specifically, I want the options in ComboBox0 to change depending on what I select in ComboBox1. And I don’t want to wait for an AJAX round trip every time I change the selection.

So, suppose we have two local variables, both of which are lists of NameValuePair, and suppose they are initialised with data.

Here’s a pic of the variables:

And here’s the code that initialises them (lazy, I know, but it’ll do):

First I’m importing JQuery, because I’m lazy and I find it helpful. But don’t get caught up with the JQuery stuff. It’s not the point of this post.

The code in question is divided into two parts:

First javascript that runs on the server, this is the chunk enclosed by pointy hashes (<# … #>).

And second, javascript that runs on the browser (the rest).

This is the conceptual leap I had to make, in Teamworks, not all javascript is equal, there’s the TW stuff and the plain old JS stuff. One executes on the server, before the coach is served, the other one is JS as we know it, for the browser.

With this in mind we can do all sorts of funky stuff.

And the best way to grok what’s happening here is to look at the source as served to the browser. So, I’m running the coach, I’m asking IE to show me the page source, and here’s the relevant bit of code:

The key thing to notice is how the items assignments work. The browser shows you how, within the conditional statement, the ‘items’ array is populated with JSON objects, but these JSON objects are actually created on the server, based on tw variables!

So basically what we are doing within the pointy hashes is generating the javascript that ultimately runs on the browser.

And once you crack that concept, well, that’s where the fun starts, really :-)