Thursday, 30 October 2014

X minutes ago functionality using jquery and knockout

In this article I am going demonstrate simple time ago functionality by using jquery.timeago plugin and knockout js.

1)      Create a HTML page and add the jquery, jquery.timeago and knockout library:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-timeago/1.4.0/jquery.timeago.min.js"></script>

 

2)      Create a viewmodel and a custom binding handler in knockout:

    <script>

        $(function () {

 

            var viewModel = {

 

                arr: [{

                    msgdate: new Date()

                }, {

                    msgdate: new Date()

                }]

            };

 

            ko.bindingHandlers.timeago = {

                update: function (element, valueAccessor) {

                    var value = ko.utils.unwrapObservable(valueAccessor());

 

                    var $this = $(element);

 

                    $this.attr('title', value.toISOString());

 

                    if ($this.data('timeago')) {

                        var datetime = $.timeago.datetime($this);

                        var distance = (new Date().getTime() - datetime.getTime());

                        var inWords = $.timeago.inWords(distance);

 

                        $this.data('timeago', { 'datetime': datetime });

                        $this.text(inWords);

                    } else {

                        $this.timeago();

                    }

                }

            };

 

            ko.applyBindings(viewModel);

        });

    </script>

3)      Bind knockout viewmodel with a div in html to display and automatically update the time.

    <div data-bind="foreach: arr">

        <div class="timeago" data-bind="timeago: msgdate"></div>

    </div>

 

Thanks for reading this article.

Read more articles.

 

1 comment:

Nannie Co Pam said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.