Using Knockout.js how do bind a Date property to a HTML5 date picker?

后端 未结 8 698
南旧
南旧 2021-01-04 00:37

(this only works in Chrome at the moment as most browsers don\'t yet implement date picker for input type=\"date\")

In the following example MyDate starts o

8条回答
  •  佛祖请我去吃肉
    2021-01-04 01:15

    Based off of Ryan's answer above, this works a little nicer with newer ko/chrome widgets. It also strips the time part of the date.

    ko.bindingHandlers.datePicker = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            // Register change callbacks to update the model
            // if the control changes.
            ko.utils.registerEventHandler(element, "change", function () {
                var value = valueAccessor();
                var target_date = element.valueAsDate;
                var truncated = new Date(target_date.getFullYear(), target_date.getMonth(), target_date.getDate());
                value(truncated);
            });
        },
        // Update the control whenever the view model changes
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var value =  valueAccessor();
            var unwrapped = ko.utils.unwrapObservable(value());
            if(unwrapped === undefined || unwrapped === null) {
                element.value = '';
            } else {
                element.valueAsDate = unwrapped;
            }
        }
    };
    

提交回复
热议问题