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.

 

No comments: