目次

Version 1, last updated by sroebuck at Nov 02 04:28 UTC

Mapping server functions to client actions

The basic principle

If you want to execute a function on the server when a client clicks on a link or a button, you need to associate your server function with the link. Lift does this by associating a randomly named HTTP Request parameter with a Scala function. When the server identifies a request with the named parameter it looks up the function associated with it and runs that function.

If you want to implement this kind of functionality in your own widgets then you probably want to make use of the S.fmapFunc function.

S.fmapFunc

fmapFunc takes two parameters. The first is the function that is to executed on the server when the link is clicked. The second is a function that generates the link code on your web page that will allow the user to execute that first function.

Let's take a very simple (although somewhat pointless) example.

import net.liftweb.http.S

S.fmapFunc(() => println("Hello")) { linkName =>
  val linkUrl = "test.html?" + linkName + "=_"
  <a href={linkUrl}>Click me</a>
}

Here the first parameter of the call to fmapFunc is a function:

() => println("Hello")

which takes no parameters and prints "Hello" to the console. Clearly this is pointless but it helps to keep the example simple!

The second parameter is also a function:

{ linkName =>
  val linkUrl = "test.html?" + linkName + "=_"
  <a href={linkUrl}>Click me</a>
}

which is given the random name assigned to your server function (above) by fmapFunc and allows you to assemble the code to be inserted into your page. In this particular case the code creates a link to the page "test.html" with the link parameter appended to it and wraps this round the text "Click me".

So, we would embed this call to fmapFunc within a snippet producing a page on our web site. The function would return the snippet of HTML code to generate a link with a precoded name which has been associated with the first function. When the user clicks on the link, as well as returning the web page requested ("test.html") the function which prints "Hello" to the console is also called on the server.