Mason Components for AJAX

David P. Bushong

AvantGo/iAnywhere, Inc.

Overview

Your Tools

What is Mason?

Mason is a Perl app-server


You can embed Perl code in your HTML and build OO-style components which inherit and extend functional components of your site.

Mason: Embed Perl in HTML

<html><body>
What do you get when you multiply six by nine?
<br/>
<% 6 * 7 %>
</body></html>

Mason: Calling Components


From inside HTML:
<& some-comp, arg1 => 'value', arg2 => 'value' &>

From inside a Perl block:
$m->comp('some-comp', arg1 => 'value', arg2 => 'value'

On a line by itself:
<ul>
% for my $row (@rows) {
 <li><% $row->{name} |h %></li>
% }
</ul>

Mason JavaScript Escaping

Mason makes HTML and URI encoding easy with |h and |u; make it equally easy for JavaScript with |j:

  $m->interp->set_escape(j => sub {
    my $str = shift;
    $str =~ s/\\/\\\\/g;
    $str =~ s/'/\\'/g;
    $str =~ s/\n/\\n/g;
    $str
  });

What is AJAX?

Asynchronous JavaScript And XML

AJAX 101

First and foremost, don't reinvent the wheel: use prototype.js or a similar JavaScript framework

Receiving AJAX Data

Data can be received and used a number of ways:

Receiving JSON

JavaScript Over Network (JSON)

Receiving XML

XML (the X in AJAX)

Receiving HTML

An HTML snippet to insert/replace into page using innerHTML

Overview

Don't Repeat Yourself

Avoiding duplication of code is a very, very good thing (D.R.Y.)
There are many tools and techniques available to avoid duplication in web development:

Reusing Existing Code

Overview

Survive JavaScriptlessness

Modern websites should perform gracefully without JavaScript

HTML for !JavaScript

Perl for !JavaScript

Overview

Cliché Example

Layout Overview

Directory layout:
 action/ -- HTTPable pages with no data (AJAX or 302)
   autohandler -- turns off header/footer
   delete-post -- deletes the given post id
   edit-post -- updates (currently just creates) a post
 comp/ -- non-HTTPable HTML snippets
   post -- a complete form or display post
   field -- a field for such a post
 func/ -- non-HTTPable Mason code
   setup -- shared setup code for all pages in the app
 includes/ -- browser includes (JS & CSS)
   masonblog.css -- stylesheet for app
   masonblog.js -- custom js for app
   prototype.js -- Prototype library
   scriptaculous/ -- Scriptaculous libraries
 autohandler -- func/setup + header/footer
 index.html -- index page (currently only "real" page!)

HTML Subsection Components

MasonBlog™ will have two non-request HTML components:
  1. HTML snippet for an individual post
  2. HTML snippet for an individual field of a post

Field HTML Component

[comp/field]

Post HTML Component

[comp/post]

Action Components

Alternative Approach

Overview

Be Secure

Overview

Links