Your First Server-side JavaScript Application / Page 2 | WebReference

Your First Server-side JavaScript Application / Page 2


[prev]

Your First Server-side JavaScript Application [con't]

The Jaxer.Dir module of file system utilities is the JavaScript equivalent to Visual Basic's FileSystemOject. We need to use it to retrieve all the files in the posts directory. As each file is read by the mapped anonymous function, the formatPost() function is called to convert their contents into HTML:


The Showdown.converter class has a method called makeHtml() that accepts a string parameter containing specially formatted plain-text. The nice thing about using a tool like Markdown is that its formatting syntax keeps the original text as readable as possible. In fact, Markdown's syntax is largely based plain text email conventions. Here's a sample:

Is converted to:

We only need one Showdown.converter class to convert all the posts, so rather than create one every time the function is called, I suggest forming a closure around the formatPost() function so that the Showdown.converter object will be retained in memory for the duration of the page's life. The showdown variable is now static, as it does not get garbage collected once the function has finished executing:

Each post is included in its own <DIV> element and appended to the main posts <DIV>. The Prototype $() function is used to facilitate referencing the parent <DIV>.

A trick to creating the script tags is to use the <JS> (Wrap in JS) button (furthest right on the HTML tab, directly over the code window ):

Figure 9

Enter "server" for the runat option. Any code that was selected when you clicked the Wrap in JS button will now be enclosed by <SCRIPT> tags:

Figure 10



Including the JS Libraries

We still have to add references to the Prototype and Showdown libraries to make them available to the blog.html page. To add a script to the HTML source, click the <JS button with the arrow above it, on the left of the <JS> (Wrap in JS) button. Enter "lib/prototype/prototype.js" and "lib/showdown/showdown.js" for the script src properties and "server" for the runat options:


Viewing the Page

By default, page output is viewed using the Built-in Preview and the Jaxer internal severs. There are two preview tabs to choose from, which mimic Firefox and Internet Explorer, the two major browser types.

Figure 11



The blog page can be made more attractive by using a CSS stylesheet without any alteration of the source files whatsoever. I included one with the project files.

That concludes today's tutorial. From here, we'll extend the project to add a page where posts can be written and previewed, re-ordered/renamed, and move to using a database instead of text files.

Original: July 30, 2009


[prev]