CoffeeScript with Backbone.js Example - Violet Hill

I have been spending sometime researching development strategies for building heavy Javascript application. I have been having some fun playing with backbone.js and coffeescript. I did not find some good tutorials that explains combine usage of these two awesome projects, so I thought of writing one myself.

Before we start, here is a quick intro about Backbone.js and Coffee Script from from their main website itself.

  1. Backbone.js: Backbone supplies structure to JavaScript-heavy applications by providing modelswith key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.

  2. Coffee Script: CoffeeScript is a little language that compiles into JavaScript. Underneath all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

In order to demonstrate usage of backbone.js and coffeescript, let me first describe you a simple example that we going to build today. You can see the final build example here. Basically, we will build a color-box configurater which takes size and color for square box to be drawn. Changes in the configuration should reflect in real time on screen. This type of functionality you see in any visual designer part of an IDE.

Coffeescript and Backbone.js example


Example consist of following parts:

Configuration Model

It basically contains three configuration properties, i.e. height, width and color of the box. We create ConfigModel class which inherits Backbone.Model class and its initialize method (which gets invoked when an instance is created) sets up the default values of the three properties. 

class ConfigModel extends Backbone.Model
  initialize: ->
    @set 'color': 'blue', 'width': '100', 'height': '100'

Configuration View

This view contains two input text boxes which are initialized with default values. This view is responsible for capturing inputs and updating the underlying model. We define two form fields color-input and width-input for taking color and size of the square. Note the identifiers (color-input/width-input) of these two elements and identifier (config-input) of the config container as they will be used coffee script part of the code.

ConfigInputView class defines the presentation layer of the configuration input and it inherits from Backbone.View class. Initialize method creates a linking between the underlying model with this instance of ConfigInputView class. Events field of the class basically binds keyup events on both the input boxes to updateConfig function. updateConfig function simply updates the underlying model’s three properties height, width and color. Note the thick arrow here “=>” which specifies that updateConfig function should be invoked in context of this instance of ConfigInputView. 



This view is responsible for presenting a single colored box as per the configuration. This view responds to changes on configuration model. Another point to note here is there can be more than one instance of such views and all of them respond to changes in the configuration. We define ColorBoxView which inherits from Backbone.View. Initialize method of the view create a compiled class from a template which is also defined below. We define a method render which simply redraws the content of color box by generating HTML for the containing element from current configuration. Note we bind render method to be invoked on any change event on the underlying model. The underlying model is config model which gets changed on every keystroke in any of the two input boxes. Render function again defined using thick arrow “=>” makes sure that render function is invoked in context of ColorBoxView instance.

This is the HTML template file that we use for a color box presentation. We are using jquery template library. Two data pieces ${width} and ${color} are filled in the render function to generate the template.

<script type="text/x-jquery-tmpl" id="color-box-template">
     <div style="margin: 20px; float: left;height:${width}px; width: ${width}px; background-color: ${color}; border: 2px solid;">



Controller is kind a core which binds everything together basically the above three components together. Controller class inherits from Backbone.Controller class and instantiates one instance of ConfigModel, ConfigInputView each and five instances of ColorBoxView. Each of the ColorBoxView gets ConfigModel instance as underlying model.

class ColorBoxController extends Backbone.Controller
    initialize: ->
       model = new ConfigModel
       color_input = new ConfigInputView 'el': $('#config-input'), 'model': model
       for x in [1..5]
          view = new ColorBoxView {model: model}
          $('#color-boxes').append view.render().el


Lastly we define a global init method which create an instance of ColorBoxController and is invoked on documentLoad event of JQuery.

init = ->
    cbl = new ColorBoxController
$(document).ready init

I am sure you will have a few questions about the post, please comment below or tweet me @sunil

Facebook Python Library Documentation - Violet Hill

This weekend , I spent sometime in exploring documentation tools available in python. I think Sphinx is the best documentation project I have ever come across. Python Docs itself uses Sphinx for documenting Python.

I thought of trying Sphinx for documenting official Facebook Python SDK. After spending some serious 4-5 hours, here it is:

Hope you guys like it. I plan to keep it updated with more writeups.


Parsing signed_request parameter in Python based Facebook Canvas application

Recently Facebook announced a new way to passing user information who is viewing your Facebook canvas application using “signed_request” parameter which is implemented on top of new signature scheme based on OAuth2.0 proposal. Facebook documentation describes “signed_request” as

The signed_request parameter is a simple way to make sure that the data you’re receiving is the actual data sent by Facebook. It is signed using your application secret which is only known by you and Facebook. If someone were to make a change to the data, the signature would no longer validate as they wouldn’t know your application secret to also update the signature.

Facebook’s python-sdk does not support parsing request parameter. Today at work, I had to write this piece of code snippet for parsing “signed_request”, so thought of sharing it here.

I know there is some cryptic code in base64_url_decode because translate, maketrans does not work that well with unicode strings. Anyways, if you have any questions, just drop a line in the commments below or message me @sunil.

Pankhon ko... Hawa zara see lagne do....

Its been quite a while since I wrote my last blog post and for a change, this time I am not going to talk anything technical :). Actually, the idea of writing this blog post got triggered from the feeling that I had when I finished watching “Udaan -by Anurag Kashyap’s production house” at Inox today. Then, when I came home, 3 Idiots was being screened on TV. There’s been quite a few movies that I can count which shivered me from inside and forced me into thinking hard about life and whether I AM LIVING IT RIGHT ? These are some of the movies which shake old age fundamentals which most of us have been brought up with.

So in today’s blog post, I am going to celebrate this feeling of freedom and “TAKE ON THE WORLD” spirit and would like to refresh the thoughts and spirit that these movies carry. The best song to set the theme would be “Pankhon ko…” from Rocket Singh. Its a beautiful song and with so thoughtful lyrics by Jaideep Sahni. Enjoy!!!

Pankhon ko hawa zara si lagne do Dil bole soya tha ab jagne do Dil dil mein hain dil ki tammana sau Do sau hon chalo zara sa tapne do Udne do udne do Hawa zara si lagne do soya tha ab jagne do Pankhon ko hawa zara si lagne do

Dhoop khili jism garam sa hai Suraj yahin yeh bharam sa hai Bikhri huyi raahein hazaron sau Thaamo koi phir bhatakne do Udne do udne do Dil ki patang chahon mein gotey khaati hai Dheel toh do dekho kahan pe jaati hai Uljhe nahin toh kaise suljhoge Bikhre nahin toh kaise nikhroge Udne do udne do

The first one is “Rocket Singh”

The Second one is “Udaan”


The Third one is “3 Idiots”


The fourth one is “Taaren zameen par…”

 <iframe width="420" height="315" src="//" frameborder="0" allowfullscreen></iframe>

The fifth one is “Rang de basanti…”

  Guys, do share your thoughts and movies which rate high in this category! #cheers

Why StackOverFlow hates Ruby and Loves C#

No wonder why stackoverflow folks decide to go with C#, the answer is simple because C# is going to make lot of money for them :) and it works really hard for them.

If you are interested in economics of programming languages with StackOverFlow, you are going to find this one amusing.

An hour back, just out of curiosity I thought of checking out popularity of programming languages on stackoverflow. I was looking for simple representative figures to compare engagement value of programming lanugages on stackoverflow. The simplest I could think of was ‘Number of Questions tagged to each language’. I chose four languages:

  • Python
  • Ruby
  • Java
  • C#

For the simplcity, let assume that each question for a language asked on Stackoverflow generates 1 USD (I know in the long run, value of each question will be way over 1USD as it will increase over time…but lets keep it 1 USD fixed), then here are some interesting economics that each programming language creates for StackOverFlow.

1. Dollars earned so far from the four languages:  poor ruby :)


2. Dollars earned this Month: poorer ruby :)


3. Dollars earned this this week: somebody save ruby :)

stackover_dollars_earned_last_weekOn the serious note, the stats for all the four languages are interesting and puzzled me when I tried to draw some logic out of them. Oh yes, the money graphs were made using the ‘Piles of Samples’ visualization from Google. You can reach me @sunil