Knockout with Jquery UI datepicker, MM/YY only

2020-07-27 05:28发布

问题:

A knockout datepicker data binder can be found here: jQuery UI datepicker change event not caught by KnockoutJS

In order to hide the dates (which is the only thing that triggers datepicker's output), I do this for the sans knockout solution:

$(".monthPicker").focus(function () {
    $(".ui-datepicker-calendar").hide();
});
$(".monthPicker").datepicker({
    dateFormat: 'MM yy,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    onClose: function(dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1)));
    }
});

This works.

But how do I get this working with knockout's data binder?

回答1:

The solution was to update the ViewModel directly and let the changes propogate to the datepicker via the update on the binder.

    <input data-bind="datepicker: monthDate,
          datepickerOptions:
          {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) {
                var month = $('#ui-datepicker-div .ui-datepicker-month :selected').val();
                var year = $('#ui-datepicker-div .ui-datepicker-year :selected').val();
                $root.monthDate(new Date(year, month, 1));
            }
          }" />