Opa Web Chat Tutorial – Displaying the user name to the user

So I’ve been doing the Opa web chat tutorial @ http://doc.opalang.org/ and one of the tasks for you to achieve is to customize the chat so that at startup at the start of the div named #conversation, display the message “Hello, you are user xxx” where xxx is the random author name.

This was quite a challenge for me until I read the part about what do means. Basically…

Functions can take 0 or more arguments, and return one and only one value. Think of it like an automatic return statement on the first calcuation that isn’t defining a value, or has a do in front of it.

So in the end inside the start() function, I have the following line:

<div id=#conversation onready={
_  -> (
do Dom.put_at_start(#conversation, Dom.of_xhtml(<div>Hello you are user {author}</div>))
Network.add_callback(user_update, room)
)
}> </div>

Which states when the #conversation div is ready to start processing, execute the statement in the curly brackets. We then start the execution of a function that has no name (we don’t care what the name is, it’s a throw-away language construct), and in the curved brackets we describe what the function should do.

Going back to the bit about do’s at the beginning of the article, this function has two statements:

Dom.put_at_start(#conversation, Dom.of_xhtml(<div>Hello you are user {author}</div>))
Network.add_callback(user_update, room)

But due to Opa returning the first value it can in a function, imagine that the function really looks like in say php:

function() {
return Dom.put_at_start(#conversation, Dom.of_xhtml(<div>Hello you are user {author}</div>));
return Network.add_callback(user_update, room);
}

Which of course makes no sense. So you need to put a do in front of one of those statements to nullify the return that’s automatically put there, making our function look like:

function() {
Dom.put_at_start(#conversation, Dom.of_xhtml(<div>Hello you are user {author}</div>));
return Network.add_callback(user_update, room);
}

Hooray!