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");
});
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:Demo JSFiddle.
Here's an alternative answer, that utilizes a custom binding. You use it in your View like this:
The custom binding code is like this:
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:You can check out this jsfiddle for a working demo.