Last active
August 30, 2015 10:37
-
-
Save jasonmitchell/9260569 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@using Quickstart.Web.Extensions | |
@model Quickstart.Web.Models.Person | |
@section scripts | |
{ | |
<script type="text/javascript" src="/Scripts/moment.min.js"></script> | |
<script type="text/javascript" src="/Scripts/knockout.bindings.date.js"></script> | |
<script type="text/javascript"> | |
var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson())); | |
ko.applyBindings(viewModel); | |
</script> | |
} | |
<h2>Date Formatting With Moment.js</h2> | |
<div> | |
<label>Date of Birth:</label> | |
<input type="text" data-bind="date: dateOfBirth, format: 'DD MMM YYYY'" /> | |
</div> |
This file contains hidden or 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 = { | |
// https://disqus.com/home/discussion/jasonmitchellcom/binding_and_formatting_dates_using_knockout_and_moment_js/#comment-1374417079 | |
init: function (element, valueAccessor, allBindingsAccessor, viewModel) { | |
ko.utils.registerEventHandler(element, 'change', function () { | |
var value = valueAccessor(); | |
if (element.value !== null && element.value !== undefined && element.value.length > 0) { | |
value(element.value); | |
} | |
else { | |
value(''); | |
} | |
}); | |
}, | |
update: function (element, valueAccessor, allBindingsAccessor, viewModel) { | |
var value = valueAccessor(); | |
var allBindings = allBindingsAccessor(); | |
var valueUnwrapped = ko.utils.unwrapObservable(value); | |
// Date formats: http://momentjs.com/docs/#/displaying/format/ | |
var pattern = allBindings.format || 'DD/MM/YYYY'; | |
var output = "-"; | |
if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) { | |
output = moment(valueUnwrapped).format(pattern); | |
} | |
if ($(element).is("input") === true) { | |
$(element).val(output); | |
} else { | |
$(element).text(output); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment