Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 12

[ 349 ]

The footer of the page contains a link, which calls a JavaScript function. This function
matches the play_round event in the DSL and causes an AJAX call to be made to the
game server. When we get a response from the server, we read the page transition it
returns in the response and we display that page:


function playRound(player) {
var params = {
sessionId: session.sessionId,
player: player
}
event('play_round', params);
}
function event(event, params) {
var url = "http://localhost:8080/tictactoe/" +
event +
"?callback=?";
if (session.sessionId != null) {
params.sessionId = session.sessionId;
}
$.getJSON(url, params, function(response) {
session = response;
if (response.page != "players") {
$("#" + response.page + " .ui-content").html(
Mustache.render(
MustacheTemplates[response.page], response));
$("#" + response.page).trigger("pagecreate");
} else {
session.sessionId = ""
}
$.mobile.changePage("#" + response.page,
{ transition: "slide" });
});
}

The content section of each page is generated dynamically using MustacheTemplate
like the following one. The state variables transmitted from the server in JSON are
passed to the template so that we can reference any of the variables that were
defined in the DSL by name. For example, grid.0 references the grid[0] value
from the DSL:


MustacheTemplates.roundX = [
"<div class='grid'>",
"<h1 class='cell'>{{grid.0}}</h1>",
"<div class='vert-separator'></div>",
"<h1 class='cell'>{{grid.1}}</h1>",
"<div class='vert-separator'></div>",
"<h1 class='cell'>{{grid.2}}</h1>",
"<div class='horz-separator'></div>",
"<h1 class='cell'>{{grid.3}}</h1>",
Free download pdf