mercredi 21 août 2013

[Knockout] How to define which properties are serialized in JSON ?


//we have a person structure, with a first name, a last name, 
//and a full name (computed field) :
function Person(first, last) {    
    this.first = ko.observable(first);    
    this.last = ko.observable(last);    
    this.full = ko.computed(function() {
        return this.first() + " " + this.last();
    }, this);
}


  • Solution 1
//we define which properties are serialized in JSON 
//(in this case, only full) and how they are serialized 
//(in this case, a simple string) :
Person.prototype.toJSON = function() {
   //only full :
   return ko.utils.unwrapObservable(this.full); // we return a string of the value
};
var person=new Person("a","b");
console.log(ko.toJSON(person)); 
// => it will generate : "a b"


  • Solution 2
//we define which properties are serialized in JSON 
//(in this case, first + last name):
Person.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 person=new Person("a","b");
console.log(ko.toJSON(person)); 
// => it will generate : {"first":"a", "last":"b"}



Source :http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html

Aucun commentaire:

Categories