大家好我已经使用moment.js
<div data-bind="text: moment(formatDate).format('DD-MMM-YY')"></div>
但是当date为null时,它显示为invalid date
如何在此处显示空文本而不是invalid date
答案 0 :(得分:3)
您可以在text
:
<div data-bind="
text: ko.unwrap(formatDate) ? moment(formatDate).format('DD-MMM-YY') : ''
"></div>
或使用extender:
ko.extenders.formatDate = function(target, format) {
var result = ko.computed({
read: target,
write: function(newValue) {
var current = target(),
valueToWrite = !newValue || isNaN(newValue) ? '' : moment(newValue).format(format);
// only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({notify: 'always'});
result(target());
return result;
};
然后像这样使用它:
var someDateObservable = ko.observable();
var someDateObservableFormatted = someDateObservable.extend({
formatDate: 'DD-MMM-YY'
});