I am using knockout.js with the mapping plugin. I am getting some json data and using the mapping plugin to map it into my html.
In the json data is a json formatted date that I need to map into the html using the mapping plugin. Is it possible to use moment.js to format the date and then allow the mapping plugin to map it into the html? How do I get the json date, reformat it to a readable date and map it into the html?
// Here is my json formatted date
"DueDate":"\/Date(1362124800000)\/"
// Here's my data model
var viewModel;
$.getJSON('/myJsonData', function (data) {
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
// moment.js format date from json - how can this be passed to the ko.mapping?
var mo = moment("\/Date(1362124800000)\/").format("MMM Do YY");
});
Here's an alternative answer, that utilizes a custom binding. You use it in your View like this:
<span data-bind="textualDate: DueDate"></span>
The custom binding code is like this:
ko.bindingHandlers.textualDate = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
var textContent = moment(valueUnwrapped).format("MMM Do YY");
ko.bindingHandlers.text.update(element, function() { return textContent; });
}
};
This is convenient because you can use this binding for all Date observables, not just DueDate
. For example, suppose your model gets extended with other dates, you can easily do this without having to modify your view model:
<span data-bind="textualDate: StartDate"></span>
<span data-bind="textualDate: RevisedDate"></span>
<span data-bind="textualDate: DueDate"></span>
<span data-bind="textualDate: WeWillGetSuedPassedThisDueDate"></span>
You can check out this jsfiddle for a working demo.
The mapping.fromJS
method takes a mapping options object in its second argument.
You can provide there a create function (Customizing object construction using “create”) for the DueDate
where you do the date conversion:
var data = {
"DueDate": "\/Date(1362124800000)\/"
}
var mappingOptions = {
DueDate: {
create: function (options) {
return moment(options.data).format("MMM Do YY");
}
}
};
viewModel = ko.mapping.fromJS(data, mappingOptions);
Demo JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With