Tri Vuong's Blog

Rants about Javascript, Rails, user interface design and other things

Some Webkit issues while developing a mobile website and how to fix them

Last month, I was helping my company Yellowpages with the launch of ProSelect, a program that aims to help consumers submit requests and choose qualified providers/contractors to handle their needs. I was working on the mobile website and found out a few issues/tricks that I would like to share in this post. Most of them are Webkit related issues, specifically mobile Safari and the default browser on Android (2x and 4x).

1. Things appear juddering, flashing in mobile Safari

Remedy: add -webkit-backface-visibility: hidden

2. Elements using ‘border-box’ box content make scrollbars appear when changing orientation of the device

Remedy: make sure the parent container have “overflow: hidden”

3. Returning a function value after calling “alert” causes mobile Safari to hang

Remedy: wrap the “alert” call in a setTimeout function. I was using 200 for the delay and it worked fine.

4. CSS3 -webkit-transform:rotate(x-deg) doesn’t work in Android 2x

Remedy: add a -webkit-transform: translate3d(0, 0, 0) to the parent element. Note, this issue occurred to me while I was testing in Galaxy S2 Note.

5. input[type=date] doesn’t work in the default Android browser (4x)

Remedy: unfortunately, at the time of this writing (April 2013) the implementation of input[type=date] is very inconsistent and buggy across all the browsers (mobile Safari, FF for Android, Chrome for Android, default Android browser etc). One way to fill the gaps and be consistent is to use a library like mobiscroll (

6. Flashes and dark patches appear while scrolling a page in the default Android browser

Remedy: this issue happened to me while I was looking at a page that had a list of 120~ items, each of which is displayed in a box with some box-shadow applied. In the end I realized that limiting the list to 40~ items (about 3 pages) helped. Also removing the box-shadow reduced the repaint-chore for the browser and hence also helped (even though it might be against a particular design/styling interest)

7. The keyboard doesn’t go away and the cursor get stuck in textfields, textareas etc during form submission

Remedy: try document.activeElement.blur()

Nginx gotchas when used with Capistrano and SSL certificates

A couple of weeks ago, I was helping release a Rails app which requires SSL support and load balancing. The app runs on Unicorn, uses Nginx as a load balancer and Capistrano for deployment. In this post, I’ll describe the tips and tricks that I found a long the way.

First off, make sure you don’t have this line in your deploy.rb:

set :server_list, lambda { [fetch(:app_server)] }

Otherwise, Nginx won’t start

To verify that Nginx is running, do ‘ps -elf | grep nginx’, or look into the response header

Secondly, make sure that you have

proxy_set_header X_FORWARDED_PROTO https

Otherwise, you will run into an endless redirect loop which make your site inaccessible

Make sure that you have

server_name *

Otherwise any request to will be redirected to (yes this was shown in my browser address bar)

To ensure that you can grab the IP address of the client connecting to your site (and not your server instance), you need

proxy_set_header X-Real-OP $remote_addr

In order to support both ‘http’ and ‘https’, you should have these lines in the location /

Introducing Github Issues Ember, an Ember.js powered application

The What

Github Issues Ember is an application that demonstrates the power of Ember JS which is inspired by the original Github Issues application by 280 North.

The Why

I’ve heard about Ember.js a long time ago, when it was still Sproutcore. I never really knew how to use it partially because of its steep learning curve. The tutorials and examples I found were very basic, introductory and simple. They all have a few textfields, some bindings, update the value of a binded field after another has been updated etc. In reality, applications are never that simple and yet I couldn’t find one that demonstrates all the aspects that I was looking for such as data binding, data validation, server side interaction and templating.

So I decided to create one.

It was a bit of an effort for me to create Github Issues Ember. Things that usually took me an hour to accomplish in another library, say Backbone JS (I use Backbone JS in my day job to build some fairly complex systems) took me 2 hours or even a day to figure out. However, it was worth it in the end. I really like certain aspects of Ember.js and am thinking of using it for my future side projects.

Another reason why I worked on this project is to expose and exchange my understanding of Ember.js to other developers out there because heck, I’m a beginner too and there might be things that I do wrong or shouldn’t do or could improve. Therefore, if you’re a developer going through the source code and realize it can be done in a better way, please let me know. I’m all ears for your 2 cents.

The Where

The application can be found here and the Github repository is
here. The application requires authentication for issue/comment creation purposes. You’ll need to fill in the email field of your Github profile (don’t worry Github protects it against spammers). If you have any problems in trying out the application, please let me know and hopefully we can work out something.

Set up omniauth Github authentication for different environments (dev, prod) in a Rails app

Recently, I’ve been developing a personal project that makes use of the Github oauth api. For this purpose, I use the devise gem with support for omniauth. I figured I’d need two different sets of credentials for Github authentication since I want to develop locally and test my app on production. It turned out pretty easy.

config.omniauth :github, ENV['GITHUB_ID'], ENV['GITHUB_SECRET'], :scope => 'user,public_repo'

Ruby can read environment variables on your computer through the ENV hash. If you’re on Mac and you the bash shell, all you have to do is to open ~/.bash_profile and add (don’t forget to restart the shell for these variables to take effect)

export GITHUB_ID="Your github app id"
export GITHUB_SECRET="Your github app secret"

(by the way, you can register your app here

To push these values to Heroku (if it’s the platform you deploy to) do

heroku config:add GITHUB_ID=[Your github app id] GITHUB_SECRET=[Your github app secret]

The technique also works for Twitter and Facebook authentication strategy.

Things I want to do in 2012

Learn Vim
Master TextMate
Become more adept with Unix, Rails, Javascript
Learn Cocoa
Learn Cappucino
Learn Objective-J and Objective-C
Learn Japanese
Enhance writing skills through blogging
Improve verbal communication
Lose some (more) weight

Redo the classic Hangman game with a new approach: Backbone JS

Backbone JS is an emerging Javascript framework that helps developers develop Javascript, front-end heavy applications. The framework is lightweight (~45 kb), actively maintained and developed, and allows the use of good design patterns such as the Observer/Subscriber pattern, dependency injection etc. In this post, I will walk you through re-creating the classic Hangman game and show you how we can divide responsibilities and tasks among the model and views as well as how they communicate with each other. The source of the application is here and the demo is here.

Let’s start by listing all the things we need to do and then break them up into small steps.

Server side

  • First, we need a to be able to generate a random word
  • We need to be able to decide whether user’s guesses are correct/incorrect and keeps track of them
  • After each guess, we want to determine whether the user has won/lost the game. If they lost, the game should give the user the answer

Client side

  • We need to be able to start a new game
  • The game should take user’s guess (i.e. which character was clicked) and passes it to the backend for processing
  • Based on response from the server, display the revealed word, disable the clicked character, and draw the hangman if applicable

1. Hangman’s backend

Since this is a very simple game, we would use Sinatra for all backend processing. The documentation of Sinatra can be found here. We’d need a Word class that generates a random word from a flat file, masquerades it, reveals parts of the word after each correct guess etc. This is how the Word class looks like.

class Word
  class << self
    def get_random
      content ="countries.txt")
      words = content.split("\n")
    def masquerade(word)
      word.each_char.inject([]) { |disguise, char| disguise << (char == " " ? " " : "&nbsp;"); disguise }
    def reveal(last_revealed_word, char_clicked, final_word)
      chars = final_word.each_char.to_a
      last_revealed_word.each_index do |i|
        last_revealed_word[i] = chars[i] if last_revealed_word[i] == "&nbsp;" and chars[i] == char_clicked
    def chars_left(revealed_word)
      revealed_word.count { |c| c == "&nbsp;" }

We also need a Game class that determines whether a guess is correct/incorrect and whether the user has won/lost the game.

class Game
  class << self    
    def win?(chars_left, incorrect_guesses)
      chars_left == 0 and incorrect_guesses < 6
    def correct_guess?(char_clicked, final_word)

And finally, the endpoints for which the front end communicates with the backend.

# Index page, pretty straightforward
get "/" do
   haml :index

# Create a new game
post "/new" do
   word = Word.get_random
   masquerade_word = Word.masquerade(word)
   session[:word] = word
   session[:incorrect_guesses] = 0
   session[:chars_left] = word.size
   session[:revealed_word] = masquerade_word
   {:word => masquerade_word}.to_json

# Determine whether a guess is correct/incorrect
post "/check" do
  final_word = session[:word]
  char_clicked = params[:char_clicked]
  correct_guess = Game.correct_guess?(char_clicked, final_word)

  if correct_guess
    session[:revealed_word] = Word.reveal(session[:revealed_word], char_clicked, final_word)
    session[:chars_left] = Word.chars_left(session[:revealed_word])
    session[:incorrect_guesses] += 1
  win =[:chars_left], session[:incorrect_guesses])

  {:word => session[:revealed_word], :correct_guess => correct_guess, :incorrect_guesses => session[:incorrect_guesses], :win => win}.to_json

# Disclose the answer to user once the game is finished
post "/answer" do
  if (session[:incorrect_guesses] < 6 and session[:chars_left] > 0)
    {:success => -1, :message => "You haven't finished the game yet"}.to_json
    {:success => 1, :answer => session[:word]}.to_json

2. Hangman’s front end

As mentioned earlier, we need a mechanism to interact with the backend to post information and get response from. In the world of Backbone JS, this can be achieved using a model. Therefore, we will create a Game model to handle that. In addition, we need:

  • An ‘optionsView’ that lets player start a new game or get the answer
  • A ‘wordView’ that shows the initial masked word and reveal the characters accordingly after each correct guess
  • A ‘charactersView’ that displays all the characters (A to Z)
  • A ‘hangmanView’ that draws the Hangman after each incorrect guess
  • An ‘answerView’ that shows the answer once the game is finished
  • A ‘stageView’ that displays the game result

These views subscribe to the Game model’s events and will act accordingly.

i) First, the Game model

$(function() {
  window.Game = Backbone.Model.extend({
    defaults: {
      threshold: 6
    initialize: function() {
        win: false, 
        lost: false
    new: function() {
      var _this = this;
        url: "/new",
        type: "POST",
        success: function(response) {
          var json = $.parseJSON(response);
          _this.set({lost: false});
          _this.set({win: false});
          _this.trigger("gameStartedEvent", json);
    check: function() {
      var _this = this;
      if (_this.get("lost") || _this.get("win")) return;
        url: "/check",
        type: "POST",
        data: {char_clicked: this.get("char_clicked")},
        success: function(response) {
          var json = $.parseJSON(response);
          if (json.incorrect_guesses >= _this.get("threshold")) _this.set({lost: true});
          if ( _this.set({win: true});
          _this.trigger("guessCheckedEvent", json);
    get_answer: function() {
      var _this = this;
      if (!_this.get("lost")) return;
        url: "/answer",
        type: "POST",
        success: function(response) {
          var json = $.parseJSON(response);
          _this.trigger("answerFetchedEvent", json);

The model is pretty straightforward, it has 3 attributes ‘win’, ‘lose’, and ‘threshold’ which is the maximum number of incorrect guesses. When the game is initialized, the player neither wins nor loses so ‘win’ and ‘lost’ are both set to false.

When a new game is started, the model will post a request to the server and on the success callback, triggers the “gameStartedEvent” so that the views can catch and handle accordingly. The same logic takes place when checking the guess as well as getting the answer.

Now that we have the Game model that can trigger events, let’s see how the views handle them.

ii) The ‘optionsView’

This view contains a ‘New game’ button and will delegate the action of creating a new game to the model. I always like to bind my views to an existing element on the page instead of creating them on the fly, so my ‘el’ here is a DOM element which already exists on the page. Upon being initialized, this view sets up 2 listeners for the ‘gameStarted’, and ‘guessCheckedEvent’ which specify the actions that will happen when these events are triggered.

$(function() {
  window.OptionsView = Backbone.View.extend({
    el: $("#options"),
    initialize: function() {
      this.model.bind("gameStartedEvent", this.removeGetAnswerButton, this);
      this.model.bind("guessCheckedEvent", this.showGetAnswerButton, this);
    events: {
      'click #new_game': 'startNewGame',
      'click #show_answer': 'showAnswer'
    startNewGame: function() {;
    removeGetAnswerButton: function() {
    showGetAnswerButton: function(response) {
      if (response.incorrect_guesses == this.model.get("threshold")) {
        this.el.append('<input type="button" id="show_answer" class="action_button" value="Show answer" />');
    showAnswer: function() {

iii) The ‘wordView’

This view uses a Handlebars template to display the initial word (with empty spaces to be filled) as well as the revealed word after each correct guess. I also register a Handlebars helper called ‘displayCharacter’ which you will find here (at the very end)

$(function() {
  window.WordView = Backbone.View.extend({
    el: $("#word"),
    initialize: function() {
      this.model.bind("gameStartedEvent", this.render, this);
      this.model.bind("guessCheckedEvent", this.displayGuessResult, this);
    compileTemplates: function() {
      var template_source = $("#word_template").html();
      this.template = Handlebars.compile(template_source);
    render: function(response) {
      var html = this.template({characters: response.word});
    displayGuessResult: function(response) {
      var html = this.template({characters: response.word});

iv) The ‘charactersView’

This view displays the A-Z characters and handles player’s click events. In other words, when a player clicks on a character, the view delegates the check action to the model. Once the model has posted to the server and notified the view the result of the check, the view will then disable the clicked character depending on whether that was the right move or not.

$(function() {
  window.CharactersView = Backbone.View.extend({
    el: $("#characters"),
    initialize: function() {
      this.model.bind("gameStartedEvent", this.render, this);
      this.model.bind("guessCheckedEvent", this.disableCharacter, this);
    events: {
      'click .character': 'charClicked'
    compileTemplates: function() {
      var character_template = $("#character_template").html();
      this.character_template = Handlebars.compile(character_template)
    render: function() {
      var chars = this.character_template({characters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'W', '&']})
    charClicked: function(event) {
      if (this.model.get("lost")) return;
      var target = $(;
      this.model.set({char_clicked: target.attr("char"), target: target});
    disableCharacter: function(response) {      

v) The ‘hangmanView’

Pretty straightforward, I hope. This view draws the hangman progressively after each incorrect guess (by turning the body parts from hidden to visible)

$(function() {
  window.HangmanView = Backbone.View.extend({
    el: $("#ground"),
    initialize: function() {
      this.model.bind("gameStartedEvent", this.clearHangman, this);
      this.model.bind("guessCheckedEvent", this.drawHangman, this);
    setupSelectors: function() {
      this.body_parts = [$("#head"), $("#body"), $("#right_arm"), $("#left_arm"), $("#right_leg"), $("#left_leg")];
    drawHangman: function(response) {
      if (!response.correct_guess) this.body_parts[parseInt(response.incorrect_guesses)-1].css("visibility", "visible");
    clearHangman: function() {
      $("#string").css("visibility", "visible")
      _.each(this.body_parts, function(part) {
        part.css("visibility", "hidden");

vi) The ‘answerView’

Displays the correct answer once the game is finished, and hides it once a new game is started.

$(function() {
  window.AnswerView = Backbone.View.extend({
    el: $("#answer"),
    initialize: function() {
      this.model.bind("gameStartedEvent", this.hide, this);
      this.model.bind("answerFetchedEvent", this.render, this);
    render: function(response) {
      if (response.success == 1) {
        this.el.html("Answer: " + response.answer).show();
      } else {
    hide: function() {

vii) The ‘stageView’

Displays the game result. You might wonder whether we really need this view. Why can’t we just display the game results in one of the other views? The reason being I didn’t want to pollute the other views with responsibility that doesn’t really belong to them. That’s why I wanted to have this view to handle the result as well as other top level functionalities that the game might introduce in the future.

$(function() {
  window.StageView = Backbone.View.extend({
    el: $("#stage"),
    initialize: function() {
      this.model.bind("guessCheckedEvent", this.showGameResult, this);
    showGameResult: function(response) {
      if (response.incorrect_guesses == this.model.get("threshold")) alert(i18n.lose_message);
      if ( alert(i18n.win_message);

Lastly, we need to bring everything to life. By that, I mean initializing the views, inject them with the Game model and off you go. The model will interact with the server every time a DOM event (such as click) happens, gets back the response, generates events. Since the views are listening to the Game model’s events, they will know what to do and will act accordingly. Here is one of the great things I like about Backbone. It allows you to inject dependencies to your view at runtime. An explanation to what dependency injection is and its benefits can be found here.

$(function() {
  var game            = new Game
  var options_view    = new OptionsView({model: game})
  var characters_view = new CharactersView({model: game})
  var word_view       = new WordView({model: game})
  var hangman_view    = new HangmanView({model: game})
  var answer_view     = new AnswerView({model: game})
  var stage_view      = new StageView({model: game})

What we’ve learned from this example (a reflection of my understanding of Backbone JS and the way I use it)

  • Backbone JS helps us seperate the business logic from presentation logic. Things that talk to the server, validation etc go into the model. Things that happen in the view such as a user’s click event should be in the view
  • In Backbone, views don’t talk to each other directly, nor do they embed each other. Instead they communicate with the model through the subscriber/observer pattern (Note: this is my way of using Backbone, it is NOT a gospel truth). This provides us a mechanism to decouple things
  • Event binding is easy to use and grasp, plus event delegation is handled extremely well
  • Backbone JS is agnostic to the underlying DOM manipulation interface. You can use whatever you like, jQuery, Zepto, Prototype or MooTools
  • The choice of a templating language is totally up to you, you can plug in Underscore, Handlebars, Mustache, jQuery templates or anything you see fit
  • Backbone promotes a good way to structure your application, good design patterns which are easy to follow and easy to get new developers to get up to speed with which is really important in terms of understanding legacy code and bringing on new people in your team

And that is it. I hope you find my post useful and have fun building applications in Backbone. If you have any comments or questions, I can be reached at trivektor at

Javascript quirks

Inspired by this post I would like to compose a list of Javascript quirks for my self and anyone else interested. Here comes the bride…

(1, 2, 3) = 3

1 + + 1 = 2

1 + – + 1 = 0

1 – – 1 = 2

1 – – – 1 = 0

+ + + + 1 = 1

– – – 3 = -3

+[] = 0

2 + [] = “2”

2 + + [] = 2

1 + false = 1

1 + true = 2

a = 1; a+++1; alert(a) //2

1 + [1] = “11”

1 == [1] //true

Simple programming rules I like

It was while reading this post that I found a comment by Patrick Balleux which I really like and want to share with everyone

“Good coding style is often limited by the language and the time allowed to solve the problem.

Bad code is often generated with short dead lines and by dreamers. When I say “dreamers”, I’m thinking about those trying to prove the world that they can create an amazing new framework where their code will solve everything.

I follow those simple rules:

– make it work, then make it clean, then make it fast
– if it looks cool, this is a bad idea
– if it does everything, it will do nothing
– if it need comments, it’s badly coded

Code should be easy to understand. Would you read a book if you were required to use a dictionary to understand each line? Same applies to code.

The quality of code often represents the understanding of the issue to solve. The first step if to have a clean design, well documented. No coding should happen if you cannot understand the requirements first.

My 2 cents”
Patrick Balleux

Learning Scala: Array and List


Define an array

  • var myArray = new Array[Int](3) (the type of myArray is inferred)
  • var myArray:Array[Int] = new Array[Int](3) (explicit type declaration)
  • var myArray = Array.apply(1, 2, 3)
  • var myArray = Array(1, 2, 3)

Accessing an element in an array

  • myArray(0)
  • myArray.apply(0)

Changing an element in an array

  • myArray(0) = 100
  • myArray.update(0, 100)


Define a list

  • var list = List(1, 2, 3)

Append an element to a list

  • list = 1 :: list

Some useful list methods

  • => element + 1) (increments each list element by 1)
  • list.exists(element => element < 0) (determines whether the list contains a negative element)
  • list.filter(element => (element % 2) == 0) (filters even numbers)
  • list.isEmpty (self explanatory)
  • list.head (returns the first element of a list)
  • list.last (returns the last element of a list)
  • list.reverse (returns a list with its elements in reverse order)
  • list.remove(element => (element % 3) == 0) (remove all multiples of 3 from the list)

Get every new post delivered to your Inbox.

Join 168 other followers