我如何设法处理最初为空的时间戳?我需要将月份和年份设置为步骤。下拉列表中的月份和文本输入字段中的年份。
在这里摆弄:http: //jsfiddle.net/DrHyper/azf74/
JS:
function AgreementData(data) {
var self = this;
data = data || {};
self.effectiveDate = ko.observable(data.effectiveDate || "");
self.effectiveDateMonth = ko.computed({
read: function () {
var dateR = new Date(self.effectiveDate());
return dateR.getMonth();
},
write: function (value) {
var dateW = new Date(self.effectiveDate());
dateW.setMonth(value);
self.effectiveDate(dateW.getTime());
},
owner: self
});
self.effectiveDateYear = ko.computed({
read: function () {
var dateR = new Date(self.effectiveDate());
return dateR.getFullYear() ? dateR.getFullYear() : "";
},
write: function (value) {
var dateW = new Date(self.effectiveDate());
dateW.setFullYear(value);
self.effectiveDate(dateW.getTime());
}
});
}
var Month = function (monthIndex, monthString) {
this.monthIndex = monthIndex;
this.monthString = monthString;
};
function AgreementViewModel() {
var self = this;
self.agreement = ko.observable(new AgreementData());
self.months = ko.observableArray([new Month(0, 'Januar'), new Month(1, 'Februar'),
new Month(2, 'Marts'), new Month(3, 'April'), new Month(4, 'Maj'),
new Month(5, 'Juni'), new Month(6, 'Juli'), new Month(7, 'August'),
new Month(8, 'September'), new Month(9, 'Oktober'), new Month(10, 'November'),
new Month(11, 'December')]);
// self.postAgreement = function () {
// var jsonData = ko.toJSON(self.agreement);
// $.post("/sam-rest/agreements", jsonData, function(returnedData) {
// // This callback is executed if the post was successful
// })
//
// };
//
// self.getAgreement = function (agreementNumber) {
// $.getJSON("/sam-rest/agreements/"+agreementNumber, function (jsonData) {
// self.agreement(new AgreementData(jsonData));
// });
//
// };
//
// Sammy(function() {
// this.get('#:action/:agreementNmb', function() {
// self.action(this.params.action);
// self.getAgreement(this.params.agreementNmb);
// });
// }).run();
}
var agreementViewModel = new AgreementViewModel();
ko.applyBindings(agreementViewModel);
HTML:
<form>
Month: <select id="effectiveDateMonth" data-bind="options: months,
optionsText: 'monthString',
optionsValue: 'monthIndex',
value: agreement().effectiveDateMonth,
optionsCaption: 'Choose...'"></select>
Year: <input type="text" data-bind="value: agreement().effectiveDateYear" placeholder="YYYY" />
<hr>
</form>