我有一个看起来像这样的视图模型:
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);
}
});
};
正如您所看到的,我有一个可写的计算可观察量,可在更新时更新startDate小时/分钟。
这是有效的,但是当它这样做时,datepicker
输入字段显示日期的长格式,而不是(例如)
2013年1月3日
这里有JSFiddle:http://jsfiddle.net/alexjamesbrown/2kSpL/9/
答案 0 :(得分: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/