Last active
September 6, 2017 10:20
-
-
Save tommck/6174395 to your computer and use it in GitHub Desktop.
a knockout binding handler for date formatting with momentjs
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
/* | |
* read-only date display with momentjs | |
* use like this: data-bind="moment: dateVar, format: 'YYYY-MM-DD'" | |
* The "format" is optional and will default to "MM/DD/YYYY" | |
*/ | |
ko.bindingHandlers.moment = { | |
update: function (element, valueAccessor, allBindingsAccessor, viewModel) { | |
var val = valueAccessor(); | |
var formatted = '**INVALID**'; // throw instead? | |
var date = moment(ko.utils.unwrapObservable(val)); | |
var format = allBindingsAccessor().format || 'MM/DD/YYYY'; | |
if (date && date.isValid()) { | |
formatted = date.format(format); | |
} | |
element.innerText = formatted; | |
} | |
}; |
Thanks @codethug, I added your change and also added checking for valid date formats. For now, I just return "** INVALID **", but when I think about it more, I'll figure out what I need to do for better error handling.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I haven't tried using MomentJS with knockout, but I like the idea.
It doesn't look like you're unwrapping the value, which means that this will fail if you are binding to an observable. See http://jsfiddle.net/tlarson/6Aggd/1/ for a failure example.
I've updated line 9 to unwrap the observable in a forked Gist:
https://gist.github.com/codethug/6423433
Here is an updated fiddle with my changes: http://jsfiddle.net/tlarson/6Aggd/2/
With this change, it will work regardless of whether dateVar is an observable or not.
If you're using KO 2.3, you can use the shorthand version:
var date = moment(ko.unwrap(val));