Created
June 3, 2021 06:53
-
-
Save groovenectar/3ad953abbd52b357ca4ede52cc4dbca9 to your computer and use it in GitHub Desktop.
Date Binding for Knoockout JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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