Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  25] [ 4]  / answers: 1 / hits: 70682  / 12 Years ago, thu, march 8, 2012, 12:00:00

I've written a few custom bindings using KnockoutJS. I'm still unsure when to use ko.utils.unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value. Looking at the section on Knockout about creating custom bindings, they have the following syntax:



var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);


In this case, they invoke the observable via () but then also call ko.utils.unwrapObservable. I'm just trying to get a handle on when to use one vs. the other or if I should just always follow the above pattern and use both.


More From » knockout.js

 Answers
15

You should use ko.utils.unwrapObservable in cases where you don't know if you have been given an observable or not. This would commonly be in a custom binding where an observable or non-observable could be bound against it.



In the code that you have above, the call to valueAccessor() is not actually unwrapping an observable. It is just retrieving the value that was passed to the binding in the correct context (it gets wrapped in a function to protect it). The return value of valueAccessor() may be an observable or not. It is whatever was passed to the binding.


[#86971] Wednesday, March 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;