xdan / datetimepicker使用淘汰赛 - 无法更新" highlihted days" dynamicaly

时间:2016-10-31 21:20:00

标签: knockout.js datetimepicker

我正在使用xdan/datetimepicker,并且无法将数据突出显示为动态绑定。



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>
&#13;
&#13;
&#13;

我的代码的主要部分。检查评论。 所以主要的问题是&#34; onChangeMonth&#34;日期亮点未从&#34; self.highlightedDates&#34;更新。我做错了什么?当显示callender并获得结果时,是否可以动态更新日期突出显示?怎么做?

注意:此帖子/代码剪辑可能很有用 - xdan/datetimepicker use “momenjs” instead default “php-date-formatter”

1 个答案:

答案 0 :(得分:1)

找到结果后如何更新日历视图:

在knockout绑定中,我调用了一个方法来获取数据传递datetimepicker的HTML doom元素。

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

我添加了&#34; 然后&#34;在jquery getJson方法中的动作,在其中我更新了datapicker选项:

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

完整获取数据方法:

$.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()});
                    }
                });

现在几天的亮点就像一个魅力:)。