Added an odometer

My next task was to throw an odometer on front page i.e. on ‘/ ‘ endpoint. This odometer shows the message count i.e the total number of messages and also updates itself with a new incoming message.  Initially i didn’t knew about the about the results but they were really fascinating.

I first added the following code to the ‘/ ‘ endpoint  to get the value of the message-count and render it with index.html.

@app.route('/')
def index():
    total = dm.Message.grep()[0]
    return flask.render_template('index.html',    docs=load_docs(flask.request), total=total)

Next was to add an odometer , a Javascript and CSS library that can be used for smoothly transitioning numbers. I used it to display message-count so that it can be updated with a new message. It can be done by adding the javascript and a CSS file which can be selected from the following themes. Well to have a glimpse of what odometer is, there is a demo page that you’ll find very interesting. Do have a look at it.

I added the following code to  index.html. I have set the starting value of message count to 123456 and then it will upgrade itself to the value of total.

<h1> <div id="odometer" class="odometer">123456</div>
    <script>
        setTimeout(function(){
            odometer.innerHTML = {{total}};
        }, 1000);
    </script>
</h1>

Here’s the link to the commit i made. Also you can see below how it looks after adding the odometer to it.

Screenshot from 2014-02-06 18:16:46

After this, I want to update this total with any new incoming message. I did this with the help of websockets. Being a novice in javascript, it took me some-time to understand all this but with the help of few tutorials on websockets and a reference to boilerplate of some other app, i could have got through it.

I added the following javascript function

function WebSocketTest()
{
    if ("WebSocket" in window)
    {
        // Let us open a web socket
        var ws = new WebSocket("wss://hub.fedoraproject.org:9939");

        ws.onopen = function(e)
        {
            // Web Socket is connected, send data using send()
            ws.send(JSON.stringify({topic: '__topic_subscribe__', body: '*'}));
        };
        ws.onmessage = function (evt)
        {
            count = count + 1;
            odometer.innerHTML = count;
        };
        ws.onclose = function(e){socket=null;};
        ws.onerror = function(e){socket=null;};
   }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s