Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs undo ko.mapping.fromJS

I am aware of there is a function ko.utils.unwrapObserable() but it doesn't seem to unwrap an observable that is mapped by the ko.mapping.fromJS() at all:

console.log(listing);
listing = ko.utils.unwrapObservable(listing);
console.log(listing);

And I get the following output:

Object { __ko_mapping__={...}, title=c(), remote_id=c(), more...}
Object { __ko_mapping__={...}, title=c(), remote_id=c(), more...}

Reason I am asking for this is related to another question, basically listing is an instance of a class, which has methods reference its variables, the problem is after listing is mapped to an observable and the class methods will fail because the variables become methods.

My question is, is there a function for me to undo the mapping?

like image 556
James Lin Avatar asked Sep 28 '26 02:09

James Lin


1 Answers

What you need is the ko.mapping.toJS function (see in documentation).

It does is the exact opposite of the ko.mapping.fromJS so it turns an object with observable properties to a plain JavaScript object without any observables:

console.log(listing);
listing = ko.mapping.toJS(listing);
console.log(listing);

Object { title="..,", remote_id="...", more...}

The actual implementation of the ko.mapping.toJS is that it recursively walks through your object properties and calls ko.utils.unwrapObservable on each of them.

like image 194
nemesv Avatar answered Sep 30 '26 17:09

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!