Search code examples
knockout.jsdatetimepicker

xdan/datetimepicker using knockout - can not update "highlihted days" dynamicaly


I am using xdan/datetimepicker and can not make that data highlights were binded dynamicaly.

var MainViewModel = function(app) {
  var self = this;
  var $parent = app;

  self.dataAvailability = {};
  self.highlightedDates = ko.observable(undefined); //ko.observableArray([]);

  //Then I have method to query available data in DB, endpoint returns array like this: [2016-09-27T00:00:00.0000000+03:00,2016-09-29T00:00:00.0000000+03:00]
  self.UpdateDataAvailabilityHighlight = function(timeString) {
    var url = String.format(config.urls.dataAvailability, settings.location());
    var dTime = moment(timeString, "DD/MM/YYYY H:mm:ss").toDate();
    var id = dTime.getFullYear() + "" + dTime.getMonth();
    $.getJSON(url, data).done(function(result) {
      var highlights = [];
	  //Using lodash
      result.forEach(function(element, index) {
        highlights.push(moment(element).format("DD/MM/YYYY").toString() + ",,xdsoft_highlighted_mint");
      });

      self.dataAvailability[id] = highlights;
    })
    
	self.highlightedDates(self.dataAvailability[id] || []);    
  }


}
module.exports = MainViewModel;


self.mainView = new MainViewModel(self);

//Knockout Binding
(function (ko) {
    ko.bindingHandlers.datetimepicker = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var $element = $(element);
            var value = valueAccessor(), allBindings = allBindingsAccessor();
            var valueUnwrapped = ko.utils.unwrapObservable(value);
            var options = allBindings.dtPickerOptions || {};

            var myFormatter = {
                parseDate: function (vDate, vFormat) {
                    return moment(vDate, vFormat).toDate();
                },
                guessDate: function (vDateStr, vFormat) {
                    return moment(vDateStr, vFormat).toDate();
                },
                parseFormat: function (vChar, vDate) {
                    return vDate;
                },
                formatDate: function (vChar, vDate) {
                    var res = moment(vChar).format(vDate);
                    return res;
                }
            };

            $.datetimepicker.setDateFormatter(myFormatter);

            $element.datetimepicker({
                step: 15,
                format: "DD/MM/YYYY H:mm:ss",
                formatTime: "H:mm",
                formatDate: "DD/MM/YYYY",
                yearStart: 2000,
                yearEnd: (new Date().getFullYear()) + 1,
                highlightedDates: bindingContext.$data.highlightedDates(),	// should ne binding, but dataTimePicker looks like can not handle dynamicaly changed values
                onChangeDateTime: function (dp, $input) {
                    var date = moment($input.val(), "DD/MM/YYYY H:mm:ss");
                    date.set('second', 0);
                    var observable = valueAccessor();
                    observable(date.format("DD/MM/YYYY H:mm:ss"));
                },
                onShow: function (ct) {
                    bindingContext.$data.UpdateDataAvailabilityHighlight(ct);
                    this.setOptions({ highlightedDates: bindingContext.$data.highlightedDates() });	//Without this highlightedDates does not work
                },
                onChangeMonth: function (ct) {
                    bindingContext.$data.UpdateDataAvailabilityHighlight(ct);
                    this.setOptions({ highlightedDates: bindingContext.$data.highlightedDates() }); //Without this highlightedDates does not work
					//SO when month is changed the "bindingContext.$data.highlightedDates" still does not get/updated the data. And if we wait some time and when results are returned, the days highlights are not updated.
                }
            });

        },
        update: function (element, valueAccessor) {
            var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
            var obs = valueAccessor();
            $(element).val(moment(valueUnwrapped, "DD/MM/YYYY H:mm:ss").format("DD/MM/YYYY H:mm:ss"));
        }
    };
})(ko);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.js"></script>
<div id="main-menu" data-bind="with: $root.mainView">
  <div class="btn-group-vertical btn-block btn-group-lg">
    <div class="content-wrapper">
      <div class="input-group date">
        <label>Time</label>
        <input type="text" class="form-control" data-bind="datetimepicker: time" />
      </div>
    </div>
  </div>
</div>

There main parts of my code. Check comments. So main problem is that "onChangeMonth" the days highlights are not updated from "self.highlightedDates". What I am doing wrong? Is it posiible that days highlight was updated dynamicaly when callender is displayed and results are get? And how to do it?

Note: This post/code snipped maybe be usefull - xdan/datetimepicker use “momenjs” instead default “php-date-formatter”.


Solution

  • Found how to update calendar view when I have results:

    In knockout bindings I called method to get data passing the HTML doom element of datetimepicker.

    $element.datetimepicker({
    ...
      onShow: function (ct) {
        bindingContext.$data.UpdateDataAvailabilityHighlight(ct, true, element);
      },
      onChangeMonth: function (ct) {
        bindingContext.$data.UpdateDataAvailabilityHighlight(ct, true, element);
      },
    ...
    });
    

    I added "then" action in jquery getJson method and in it I update the datapicker option:

    $(element).datetimepicker({highlightedDates: self.highlightedDates()});
    

    Full get data method:

    $.getJSON(url, data)
                    .done(function(result) {
                        var highlights = [];
                        result.forEach(function(element, index) {
                            highlights.push(moment(element).format(config.timeFormatDate).toString() + ",Data is awailable," + config.timePickerHighlightStyle);
                        });
    
                        self.dataAvailability[id] = highlights; //Add empty data to, that it was not queried second time
                    })
                    .fail(function() { self.notificationController.addError("Failed to retrieve data availability"); })
                    .then(function () {
                        if (updateHilight) {
                            self.highlightedDates(self.dataAvailability[id] || []);
                        }
                        if (!(typeof element === "undefined")) {
                            $(element).datetimepicker({highlightedDates: self.highlightedDates()});
                        }
                    });
    

    And now days highlight works like a charm :).