27

Is there an actual difference between:

y = ko.observable("value");
x = ko.utils.unwrapObservable(y);

and:

y = ko.observable("value");
x = y();

Should I prefer one of the above and why?

mhu
  • 17,720
  • 10
  • 62
  • 93
  • 1
    possible duplicate of [When to use ko.utils.unwrapObservable?](http://stackoverflow.com/questions/9624401/when-to-use-ko-utils-unwrapobservable) – Richard Szalay May 23 '13 at 09:41
  • @RichardSzalay: You're right, missed that one. Thank you. – mhu May 23 '13 at 10:01

1 Answers1

44

The difference is that ko.utils.unwrapObservable is safe. You should use it when don't know if parameter is observable or not. For example:

function GetValue(x){
   return ko.utils.unwrapObservable(x);
}

function GetValueEx(x){
   return x();
}

var test = 5;
var y = GetValue(test) // Work fine, y = 5;
y = GetValueEx(test) // Error!

So if you exactly know that your parameter is observable you can use () otherwise use unwrapObservable.

EDIT: A shorter version of unwrapObservable has been added in knockout 2.3 - ko.unwrap

Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47