tempusdominus / bootstrap-3

Tempus Dominus Bootstrap 3
https://getdatepicker.com/5-3/
MIT License
70 stars 23 forks source link

Updated Knockout Binding for your documentation #66

Open carltierney opened 6 years ago

carltierney commented 6 years ago

I made some modifications to your knockout binding that you had on the original github project. Feel free to include it in your documentation. It handles nulls, and avoids the moment constructor warnings.

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().dateTimePickerOptions || { format: "MM/DD/YYYY"};
        var initialValue = ko.utils.unwrapObservable(valueAccessor());

        if(!options.useCurrent && initialValue){
            options.defaultDate = new Date(initialValue);
        }

        $(element).datetimepicker(options);

        //when a user changes the date, update the view model
        ko.utils.registerEventHandler(element, "dp.change", function (event) {
            var value = valueAccessor();
            if (ko.isObservable(value)) {
                if (event.date && event.date!=null && !(event.date instanceof Date)) {
                    value(event.date.toDate());
                } else {
                    value(null);
                }
            }
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            var picker = $(element).data("DateTimePicker");
            if (picker) {
                picker.destroy();
            }
        });
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {

        var picker = $(element).data("DateTimePicker");
        //when the view model is updated, update the widget
        if (picker) {
            var koDate = ko.utils.unwrapObservable(valueAccessor());
            if(koDate && typeof(koDate) !== 'object'){
                var date = new Date(koDate);
                picker.date(koDate);    
            }
        }
    }
};
Eonasdan commented 6 years ago

cool thanks

AlwaysVbNet commented 5 years ago

@carltierney I don't think these changes comply with the latest version 5.0.0. Could you PLEASE update the code?

AlwaysVbNet commented 5 years ago

@carltierney Actually there is a bug in your code:

if(koDate && typeof(koDate) !== 'object'){ var date = new Date(koDate); picker.date(koDate);
} should be: if(koDate && typeof(koDate) !== 'object'){ var date = new Date(koDate); picker.date(date);
}

also this: typeof(koDate) !== 'object') prevents it to ever enter the statement. It seems that it should be: if (koDate) only.

Please let me know.