How to link 2 Jquery UI datepickers with Knockout?

2019-07-20 14:56发布

问题:

I want to link a startDatePicker with a endDatePicker, is there a way to link them with Knockout.js ?

When the user selects a new start date, the endDatePicker would be updated setting the minDate as the new start date and regarding if the new date is after its own date it would update the current date as well?

Thanks in advance, I am trying with custom binders, but I can't get anything working.

回答1:

That code should work, when selecting a minimum date it will then set the minDate of the second datepicker to its value, vice versa for max.

$('#min').datepicker({
    onSelect: function( selectedDate ) {
    $( "#max" ).datepicker( "option", "minDate", selectedDate );
    }
})

$('#max').datepicker({
    onSelect: function( selectedDate ) {
    $( "#min" ).datepicker( "option", "maxDate", selectedDate );
    }
})


回答2:

You can use subscribe to subscribe to changes of an observable. Documentation is here: http://knockoutjs.com/documentation/observables.html#explicitly_subscribing_to_observables

var ViewModel = function() {
   var self = this;
   self.startDatePicker = ko.observable();
   self.endDatePicker = ko.observable();

   self.startDatePicker.subscribe(function(newValue) {
       // set the value on the other one
   });

   self.endDatePicker.subscribe(function(newValue) {
       // set the value on the other one
   });
}; 

The rest depends on your binding...