Generating Javascript with Scala and Lift

One of the ideas that has become popular in recent years is the concept of writing complex browser GUIs entirely in your server side language, and generating the required javascript. In Java both the Google Web Toolkit and ZK allow you to do this. You get a number of advantages from this approach:

  • Your server side language is at a higher level of abstraction than coding in javascript and hence more productive.
  • You can get some type checking done when your code is compiled.
  • You can reuse functions you’ve already written as part of your core application, and the framework will translate them to javascript as required, rather than having to rewrite them in javascript yourself.

In this article I’ll introduce the functionality that the Scala Lift framework offers for generating javascript from Scala. I’m not assuming any prior knowledge of the Lift framework so you should be able to work through the examples even if you’ve never used Lift before. However, if you’d prefer to learn the basics of Lift and sbt first, you might want to read my previous tutorial: Building your first Lift app with sbt.

Download Lift

If you’re new to Lift, download it from: http://liftweb.net/download
As the instructions say, if you change into the scala_28/lift_basic directory and run
sbt update ~jetty-run
then an empty Lift application should start.

Add a form and validation Javascript

To begin with, we’ll add a form to the main page of the app and attach some javascript to it. Open up the src/webapp/index.html and add a simple form into the body of the page:

<div class="lift:RegistrationController?form=post">
  First name: <input id="first_name"><br>
  Surname: <input id="last_name"><br>
  E-mail: <input id="email"></br>
  <input type="submit" value="Submit">
</div>

Now we need to create the snippet that will process this form. The class on the form indicates that it will be processed by a snippet called “RegistrationController” so go into src/main/scala/code/snippet and create RegistrationController.scala:

package code.snippet
import scala.xml.NodeSeq
import net.liftweb.util._
import Helpers._
import net.liftweb.http._
import net.liftweb.http.js.JsCmds._
import net.liftweb.http.js.JE._
 
class RegistrationController  {
 
	private val whence = S.referer openOr "/"
 
	def render = {
	  "type=submit" #> SHtml.submit("Register", process, 
	    "onclick" -> JsIf(JsEq(ValById("first_name"), ""), Alert("alert") & JsReturn(false)).toJsCmd)
	}
 
	private def process() = {
	  S.redirectTo(whence)
	}
 
}

Let’s break down what this snippet is doing. As with all snippets, it implements the render method to transform the html in the page template. It is using a Lift CSS selector transform (the #>) which finds the html element with the “type” attribute set to “submit”, and replaces this with a submit button generated by calling the SHtml.submit method. The first parameter to the submit method is the name of the button, the second is the function to be called when the form is sent to the server. The third parameter is a list of html attributes that the button element should have. In this case we are just creating a single attribute, the onclick one, which will invoke our javascript validation – if the first_name parameter is empty, show a pop up alert box. We call the toJsCmd method on the javascript expression to turn it into a command, because that can be implicitly converted into the html attribute that the submit method requires. You should be able to verify that this alert is shown if you try to submit the form without a first name.

Let’s extend the example slightly to show how we can edit the browser DOM. Let’s add a second button to the html template next to the first:

First name: <input id="first_name"><br>
Surname: <input id="last_name"><br>
E-mail: <input id="email"></br>
<input type="submit" value="Submit">
<input type="button" value = "Populate form"/>

In our Scala code, we’ll add some javascript to this button to populate the first name field with a default value when you click the button:

def render = {
  "type=submit" #> SHtml.submit("Register", process, 
     "onclick" -> JsIf(JsEq(ValById("first_name"), ""), Alert("alert") & JsReturn(false)).toJsCmd) &
  "type=button" #> SHtml.ajaxButton("Populate form", () => JsCmds.SetValById("first_name","John"))
}

What is this Scala doing? Well, we begin by using an & to join our chain our first CSS selector to a second one. The second CSS selector finds the html element with the “type” set to “button” and replaces it with a button created by calling the SHtml.ajaxButton method. This method takes two parameters, the first is the text to put on the button, and the second is a function to invoke when the button is pressed. We use standard Scala syntax of => to declare a function that takes no parameters and when invoked, finds the first_name element in the DOM and sets the value to “John”.

Wrap up

In this article we’ve looked at a couple of simple examples of how to generate javascript on the server, using Scala code. The basic mechanism is to create the javascript using Lift’s JsCmds and JE classes, then attach the javascript to your html using standard CSS selectors and the helper methods in the SHtml object. For more detailed examples, you can check out chapters 10 and 11 in the “Exploring Lift” book:
http://exploring.liftweb.net/master/index-10.html

This entry was posted in Javascript, Lift, Scala and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

503,610 Spambots Blocked by Simple Comments

HTML tags are not allowed.