Bootstrap 3 Datepicker - Knockout.js

Has anyone successfully used Bootstrap 3 Datepicker along with knockout.js?

I spent my day on datepickers and knockout.js bindingHandlers, but without success.

Here is my current knockout.bindingHandler:

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //when a user changes the date, update the view model
        ko.utils.registerEventHandler(element, "changeDate", function (event) {
            var value = valueAccessor();
            if (ko.isObservable(value)) {
                value(event.date);
            }
        });
    },
    update: function (element, valueAccessor) {
        var widget = $(element).data("DateTimePicker");
        if (widget) {
            widget.date = ko.utils.unwrapObservable(valueAccessor());
            widget.setValue();
        }
    }
};

And here is my view Model:

function TurbineHistoryViewModel() {
    var self = this;

    self.severity1 = ko.observable(1);
    self.severity2 = ko.observable(2);
    self.severity3 = ko.observable(3);
    self.severity4 = ko.observable(4);
    self.severity6 = ko.observable(6);

    self.fromDate = new ko.observable(new Date());
    self.toDate = new ko.observable(new Date());
}

... and here is my markup:

<div class='input-group date' id='datetimepicker1'>
    <input type='text' class="form-control" data-bind="datepicker: objVM.fromDate"/>
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

If anyone has a working example of a good datepicker and knockout.js, I will be very happy to hear about it.

+4
source share
1 answer

The solution was to find the Bootstrap DatePicker 3 binding handler found here:

Install Bootstrap Datetimepicker to JS Knockout

and then configure the locale and date format in the options:

var options = allBindingsAccessor().dateTimePickerOptions || { locale: 'da', format: 'DD-MM-YYYY' };
$(element).datetimepicker(options);

HTML:

<div class='input-group date' id='datetimepicker1'>
    <input type='text' class="form-control" data-bind="dateTimePicker: objVM.fromDate"/>
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>
+2

Source: https://habr.com/ru/post/1614864/


All Articles