Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ko.utils.unwrapObservable and ko.toJS?

Tags:

knockout.js

What are the differences between the 2?

Surely they are the same thing since an unwrapped observable strips down to a js primitive. So why have ko.toJS or vice-versa?

Also, why is there a ko.mapping.toJS? Does this not effectively do the same as ko.toJS? There seems several functions in knockoutJS which do the same thing but there must be a reason why they exist.

like image 214
jaffa Avatar asked Feb 14 '12 12:02

jaffa


People also ask

What does Ko unwrap do?

unwrap method is used to read it), the current viewModel and bindingContext. Whenever the passed value changes the binding will print updated information to console. This binding cannot be used with virtual elements (in html comments), only on real elements, since ko.

What is knockout mapping?

Knockout is designed to allow you to use arbitrary JavaScript objects as view models. As long as some of your view model's properties are observables, you can use KO to bind to them to your UI, and the UI will be updated automatically whenever the observable properties change.

What is KO in knockout JS?

KO is that it updates your UI automatically when the view model changes.


1 Answers

There are differences between them.

The ko.toJS takes an object and "opens up" and cleans the object from all observables. It does this for the entire object graph. I behaves much like a serializer which means that you'll run into problems if you have circular references for instance. It uses mapJsObjectGraph internally which is way too complex for me to fully compile in my head right now. However, I tend to use it when I need to post stuff back to the server.

The ko.utils.unwrapObservable simply determines if the value is an observable and if it is, it returns the underlying value. If not it just returns the value. It can be handy if you you are using the mapping plugin for example where you might end up with models that can have both observables and non observables.

The ko.mapping.toJS is the only one on the list that could be suspected to be somewhat duplicated in terms of its functionality. It is used to map a mapped object graph back to its original state. It looks a lot less complex than ko.toJS but I haven't used it (yet) so I honestly can't tell you more about that one. Read more about it here.

like image 194
Mikael Östberg Avatar answered Sep 18 '22 14:09

Mikael Östberg