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

后端 未结 8 693
南旧
南旧 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:16

    Here's a solution that is working for me with the latest knockoutjs, based off of the link below and modified to have a custom init function to handle updating ko.computed properties as your date value changes.

    Note that utils.formatDate is just a utility function to format the date in whatever string you want, so just replace that with your own date formatting code, whether you use momentjs or something else.

    ko.bindingHandlers.date = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {    
            ko.utils.registerEventHandler(element, 'change', function () {
                var value = valueAccessor();
    
                if (element.value !== null && element.value !== undefined && element.value.length > 0) {
                    value(element.value);
                }
                else {
                    value('');
                }
            });
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var value = valueAccessor();
            var valueUnwrapped = ko.utils.unwrapObservable(value);
    
            var output = '';
            if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) {
                output = utils.formatDate(valueUnwrapped);
            }
    
            if ($(element).is('input') === true) {
                $(element).val(output);
            } else {
                $(element).text(output);
            }
        }
    };
    
        

    BINDING AND FORMATTING DATES USING KNOCKOUT AND MOMENT JS

提交回复
热议问题