Controlling how an object is converted to JSON
http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html
by kougiland
HTML
<script src="http://rniemeyer.github.com/KnockMeOut/Scripts/jquery.tmpl.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<ul data-bind="template: { name: 'rechnungsadresse', foreach: input}"></ul>
<hr/>
<div data-bind="text: ko.toJSON(input)"></div>
<hr/>
<script id="rechnungsadresse" type="text/html">
<li>
institution:<input data-bind="value: institution" />
abteilung:<input data-bind="value: abteilung" />
firma: <span data-bind="text: organisation"></span>
name:<input data-bind='value: name' />
vorName:<input data-bind='value: vorName' />
volleName: <span data-bind="text: fullName"></span>
strasse:<input data-bind='value: strasse' />
hausNummer:<input data-bind='value: hausNummer' />
plz:<input data-bind='value: plz' />
stadt:<input data-bind='value: stadt' />
fullAdresse:<span data-bind="text: fullAdresse"></span>
</li>
</script>
JavaScript
function meineRechnungsDaten(institution, abteilung,name,vorName,strasse,hausNummer,plz,stadt) {
this.institution = ko.observable(institution);
this.abteilung = ko.observable(abteilung);
this.name = ko.observable(name);
this.vorName = ko.observable(vorName);
this.strasse = ko.observable(strasse);
this.hausNummer = ko.observable(hausNummer);
this.plz = ko.observable(plz);
this.stadt = ko.observable(stadt);
this.organisation = ko.dependentObservable(function() {
return this.institution() + " " + this.abteilung();
}, this);
this.fullName = ko.dependentObservable(function() {
return this.name() + " " + this.vorName();
}, this);
this.fullAdresse = ko.dependentObservable(function() {
return this.strasse() + " " + this.hausNummer() + " " + this.plz() + " " + this.stadt();
}, this);
}
meineRechnungsDaten.prototype.toJSON = function() {
var humanReadableData = ko.toJS(this); //easy way to get a clean copy
//delete humanReadableData.full; //remove an extra property
return humanReadableData; //return the copy to be serialized
}
var viewModel = {
input: [new meineRechnungsDaten("", "","","","","","","")]
};
ko.applyBindings(viewModel);