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: 'peopleTmpl', foreach: ones}"></ul>
<hr/>
<div data-bind="text: ko.toJSON(ones)"></div>
<hr/>

<script id="peopleTmpl" type="text/html">
    <li>
        <input data-bind="value: first" />
        <input data-bind="value: last" />
        <input data-bind="value: iii" />
         <span data-bind="text: full"></span>
    </li>
</script>

CSS

input { width: 75px; }

JavaScript

function PersonOne(first, last,iii) {
    this.first = ko.observable(first);
    this.last = ko.observable(last);
    this.iii = ko.observable(iii);
    this.full = ko.dependentObservable(function() {
        return this.first() + " " + this.last();
    }, this);
}

PersonOne.prototype.toJSON = function() {
    var copy = ko.toJS(this); //easy way to get a clean copy
    delete copy.full; //remove an extra property
    return copy; //return the copy to be serialized
}


var viewModel = {
    ones: [
        new PersonOne("", "", ""),
        new PersonOne("Sarah", "Smith"),
        new PersonOne("Ron", "Smith")
        ]
};

ko.applyBindings(viewModel);