JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://raw.github.com/neonstalwart/knockout/toJS/build/output/knockout-latest.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="https://raw.github.com/kmalakoff/underscore-awesomer/master/underscore-awesomer.js"></script>
Date: <span data-bind="text: currentDate"></span><br />
<button data-bind="click: showRoundTripCurrentDate">RoundTrip Date</button>
<button data-bind="click: showRoundTripCollection">RoundTrip Collection</button>
JavaScript
var __native_Date_toJSON = Date.prototype.toJSON;
Date.prototype.toJSON = function() {
return {
_type:'Date',
string: __native_Date_toJSON.call(this)
};
};
Date.fromJSON = function(json) {
if (json._type!='Date') { return null; }
return new Date(json.string);
};
SomeClass = (function() {
function SomeClass(int_value, string_value, date_value) {
this.int_value = int_value;
this.string_value = string_value;
this.date_value = date_value;
}
SomeClass.prototype.toJSON = function() {
return {
_type:'SomeClass',
int_value:this.int_value,
string_value:this.string_value,
date_value:this.date_value
};
};
SomeClass.fromJSON = function(json) {
if (json._type!='SomeClass') return null;
return new SomeClass(json.int_value, json.string_value, Date.fromJSON(json.date_value));
};
return SomeClass;
})();
var viewModel = {
currentDate: ko.observable(new Date()),
showRoundTripCurrentDate: function() {
var json = _.toJSON(ko.toJS(viewModel));
var json_round_trip = JSON.parse(JSON.stringify(json));
var unwrapped_view_model = _.fromJSON(json_round_trip, {properties:true});
alert("" + unwrapped_view_model.currentDate);
},
showRoundTripCollection: function() {
var collection = [new Date(), new SomeClass(1, 'two', new Date())];
var json = _.toJSON(collection);
var json_round_trip = JSON.parse(JSON.stringify(json));
var copy_collection = _.fromJSON(json_round_trip);
alert("" + copy_collection[0] + ", " + JSON.stringify(copy_collection[1]));
}
}
ko.applyBindings(viewModel);