Bootstrap datepicker with knockout.js databind

前端 未结 4 1774
耶瑟儿~
耶瑟儿~ 2020-12-04 22:25

This question is similar to knockoutjs databind with jquery-ui datepicker, but instead of the jQueryUI datepicker, I would like to use one of the Bootstrap datepickers.

4条回答
  •  -上瘾入骨i
    2020-12-04 22:46

    Here is what I Ended up

    ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
    
        var options = {
            autoclose: true,
            format: 'yyyy-mm-dd',
        }
    
        //var options = allBindingsAccessor().datepickerOptions || {};
        $(element).datepicker(options);
    
        //when a user changes the date, update the view model
        ko.utils.registerEventHandler(element, "changeDate", function (event) {
            var value = valueAccessor();
    
            if (ko.isObservable(value)) {
                var myDate = event.date;
                var month = myDate.getMonth() + 1;
                var monthText = month;
    
                if (month < 10)
                    monthText = "0" + month;
    
                var day1 = parseInt(myDate.getDate());
                var dayText = day1;
    
                if (day1 < 10)
                    dayText = '0' + day1;
    
                value(myDate.getFullYear() + '-' + monthText + '-' + dayText);
            }
        });
    },
    update: function (element, valueAccessor) {
    
        var widget = $(element).data("datepicker");
        //when the view model is updated, update the widget
        if (widget) {
            widget.date = ko.utils.unwrapObservable(valueAccessor());
            widget.setValue(widget.date);
        }
    }};
    

提交回复
热议问题