3

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?

Community
  • 1
  • 1
James Lin
  • 25,028
  • 36
  • 133
  • 233

1 Answers1

3

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359