Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Date Binding for Knoockout JS
ko.bindingHandlers.date = {
update: function(element, valueAccessor) {
// First get the latest data that we're bound to
let data = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
let value = ko.unwrap(data);
let prop = element.nodeName === 'INPUT' ? 'value' : 'innerText';
if (value instanceof Date) {
if (element.type === 'date') {
element[prop] = value.toISOString().split('T')[0];
}
if (element.type === 'time') {
element[prop] = value.getHours().toString().padStart(2, '0') + ':' + value.getMinutes().toString().padStart(2, '0');
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment