HTML and CSS Reference
In-Depth Information
dest = "/queue/" + $("#opponentName").val();
src = "/queue/" + $("#myName").val();
connect();
};
The last function call of Listing 5-9 invokes the connect() function, which
establishes the STOMP connection, displayed in Listing 5-10. The calls inside the
connect() function are provided by the open source STOMP JavaScript library that we
use: stomp.js .
Listing 5-10. The connect() Function, Establishing the STOMP Connection
// Establishing the connection
var connect = function() {
client = Stomp.client(url);
client.connect(un, pw, onconnect, onerror);
};
The client.connect API has two callback functions. The first, onconnect() , is
invoked upon successful connection; the second, onerror() , is invoked when an error
occurs.
Let's take a closer look at the onconnect() callback function. After a log to the
console that we have successfully connected, we subscribe to the queue, defined by the
src variable. This queue is named after this player. Whenever there's a message arriving
in on this queue, the callback defined as the second parameter of client.subscribe
will be executed. When the incoming message indicates that the opponent has already
picked, we set the hasOpponentPicked to true . Then, we draw the buttons representing
the opponent player's pick, but hide them if this player hasn't moved yet, shown in
Listing 5-11.
Listing 5-11. Code Rendering the Game Buttons
// Function invoked when connection is established
var onconnect = function() {
console.log("connected to " + url);
client.subscribe(src, function(message) {
console.log("message received: " + message.body);
// The incoming message indicates that the
// opponent had his/her turn (picked).
// Therefore, we draw the buttons for the opponent.
// If this user hasn't had his/her move yet,
// we hide the div containing the buttons,
// and only display them
// when this user has had his/her move too.
hasOpponentPicked = true;
if (!hasUserPicked) {
$("#opponentsButtons").css("visibility", "hidden");
 
Search WWH ::




Custom Search