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

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

    While @amakhrov answer will work (and would be even better if used writeable computed observable like sujested by @Stijn) I decided to do this using Custom Bindings.

    The main advantage of doing this is reusability - I just have to use data-bind="datePicker : MyDate" whereever I want to tie this in. I can also modify other properties of the input element so this could be really useful if binding to complex jQuery (and other) controls.

    (Read here for more pro/cons about the 3 choices to do this sort of thing)

    HTML

    
    

    JS

    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();
                value(new Date(element.value));            
            });
        },
        // Update the control whenever the view model changes
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var value =  valueAccessor();        
            element.value = value().toISOString();
        }
    };
    
    var viewModel = {    
        MyDate : ko.observable(new Date())
    };     
    
    ko.applyBindings(viewModel);
    

    See http://jsfiddle.net/LLkC4/5/

提交回复
热议问题