1

我有一个看起来像这样的视图模型:

var ViewModel = function() {
    var self = this;

    self.hourOptions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
    self.minuteOptions = [0, 15, 30, 45];

    self.formatTimeOption = function(hour) {
        if (hour < 10) return "0" + hour;
            return hour.toString();
    };

    self.startDate = ko.observable(null);

    self.startDateHour = ko.computed({
        read: function() {
            return new Date(self.startDate()).getHours();
        },
        write: function(value) {
            var newDate = new Date(self.startDate());
            newDate.setHours(value);
            self.startDate(newDate);
        }
    });

    self.startDateMinute = ko.computed({
        read: function() {
            return new Date(self.startDate()).getMinutes();
        },
        write: function(value) {
            var newDate = new Date(self.startDate());
            newDate.setMinutes(value);
            self.startDate(newDate);
        }
    });
};

如您所见,我有一个可写的计算 observable,它在更新时更新 startDate 小时/分钟。
这是有效的,但是当它这样做时,datepicker输入字段会显示日期的长格式,而不是(例如)

2013 年 1 月 3 日

JSFiddle 可以在这里找到:http: //jsfiddle.net/alexjamesbrown/2kSpL/9/

4

1 回答 1

1

我通过添加以下自定义绑定处理程序解决了这个问题,取自this answer

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {};
        $(element).datepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function() {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).datepicker("destroy");
        });

    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            current = $(element).datepicker("getDate");

        if (value - current !== 0) {
            $(element).datepicker("setDate", value);
        }
    }
};

这是一个有效的 JSFiddle:http:
//jsfiddle.net/alexjamesbrown/v6hdS/

于 2013-01-04T11:35:34.297 回答