How could I implement a fuzzy time date replacer using Knockout ?

How could I implement a fuzzy time date replacer using Knockout ?

Asked on December 24, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

    Because of the  time ago make  a cache via jQuery’s data() function ,This is not useful;

        The custom binding is  help to rectify this :

    ko.bindingHandlers.timeago = {
        update: function(element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            var $this = $(element);
            // Set the title attribute to the new value = timestamp
            $this.attr('title', value);
            // If timeago has already been applied to this node, don't reapply it -
            // since timeago isn't really flexible (it doesn't provide a public
            // remove() or refresh() method) we need to do everything by ourselves.
            if ($this.data('timeago')) {
                var datetime = $.timeago.datetime($this);
                var distance = (new Date().getTime() - datetime.getTime());
                var inWords = $.timeago.inWords(distance);
                // Update cache and displayed text..
                $this.data('timeago', { 'datetime': datetime });
                    $this.text(inWords);
                } else {
                    // timeago hasn't been applied to this node -> we do that now!
                $this.timeago();
            }
        }
    };
    

    This is the usage :

    <abbr data-bind="timeago: Posted"></abbr>
    
    Answered on December 24, 2018.
    Add Comment

        Use this code for updating a fuzzy time date replacer :

    usf.ko.bindings['timeago'] = {
        update: function(element, valueAccessor) {
            var $element, date;
            date = ko.utils.unwrapObservable(valueAccessor());
            $element = $(element);
            if (date) {
                $element.attr('title', date.toISOString());
                $element.data('tiemago', false);
                return $element.timeago();
            }
        }
    };
    

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.