zimki | documentation | search
 
Zimki Documentation - CookBook.E4X

E4X: JavaScript for XML

The Zimki JavaScript engine fully supports using E4X, meaning that you can use XML as first class data types. This allows you to write things like this:

function hello() {
  return <html>
    <head>
      <title>hello</title>
    </head>
    <body>
      <h1>Hello World</h1>
    </body>
  </html>
}
zimki.publishPath('/', hello);

Notice that there's no quotes around that chunk of HTML (JavaScript doesn't have multi-line strings; we'll get to that in a bit), meaning that the 'hello' function is not returning a string of HTML but an XML object (which happens to be valid HTML). We then publish the return value to the path '/', but you might want to play around in the JavaScript Console and just evaluate the return value of the 'hello' function instead.

Autovivification for the lazy typist

E4X allows you to do more interesting things than typing out multi-line blocks of XML though. For example, here's a different way to write the 'hello' function above:

function hello() {
  var ret = <html/>;
  ret.head.title = 'hello';
  ret.body.h1 = 'Hello World';
  return ret;
}

Not only does this involve less typing, it also involves less manual syntax checking; any autovivified nodes are automatically terminated properly so you don't have to worry about it.

Multiline strings

One thing E4X allows you to do is to fake multi-line strings. You can do something like this, for example (copy and paste this into the JavaScript Console in the Zimki Portal):

'' + <text>
We come in peace;
lay down your weapons and take me to your leader.
And take that finger out of your nose when facing an officer.
</text>;

Accessing attributes of an XML object

We saw above how to access element values of an XML object: we simply access the attribute. However, XML can have attributes too, and using E4X you can access these values too. Let's say we have a table, like so:

var hiscore = <table>
  <tr width="100%">
    <th>Team</th>
    <th>Score</th>
  </tr>
  <tr>
    <td>Arsenal</td>
    <td>10</td>
  </tr>
</table>;

We find that the table is too wide, and want to resize it to take only 50% of the width. Additionally, we want the header row to be 50px high. We can do that by directly manipulating the hiscore object like so:

hiscore.tr.@width = '50%';
hiscore.tr.@height = '50px';

Parent

CookBook