100

I'm using KnockoutJS version 2.0.0

If I'm looping through all properties of an object, how can I test whether each property is a ko.observable? Here's what I've tried so far:

    var vm = {
        prop: ko.observable(''),
        arr: ko.observableArray([]),
        func: ko.computed(function(){
            return this.prop + " computed";
        }, vm)
    };

    for (var key in vm) {
        console.log(key, 
            vm[key].constructor === ko.observable, 
            vm[key] instanceof ko.observable);
    }

But so far everything is false.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393

4 Answers4

163

Knockout includes a function called ko.isObservable(). You can call it like ko.isObservable(vm[key]).

Update from comment:

Here is a function to determine if something is a computed observable:

ko.isComputed = function (instance) {
    if ((instance === null) || (instance === undefined) || (instance.__ko_proto__ === undefined)) return false;
    if (instance.__ko_proto__ === ko.dependentObservable) return true;
    return ko.isComputed(instance.__ko_proto__); // Walk the prototype chain
};

UPDATE: If you are using KO 2.1+ - then you can use ko.isComputed directly.

RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211
  • 2
    Thank you. Do you by chance know how to tell if an observable is computed? I can determine if an observable is an observable array via `$.isArray(vm[key]())`, but do you know how to differentiate observables from a `ko.computed`?? – Adam Rackis Mar 08 '12 at 22:19
  • 7
    KO 2.1 that should be out in the next few weeks will include a `ko.isComputed` function. The code would be the equivalent to what I added to the answer above. – RP Niemeyer Mar 09 '12 at 02:36
29

Knockout has the following function which I think is what you are looking for:

ko.isObservable(vm[key])
Mark Robinson
  • 13,128
  • 13
  • 63
  • 81
3

To tack on to RP Niemeyer's answer, if you're simply looking to determine if something is "subscribable" (which is most often the case). Then ko.isSubscribable is also available.

pim
  • 12,019
  • 6
  • 66
  • 69
0

I'm using

ko.utils.unwrapObservable(vm.key)

Update: As of version 2.3.0, ko.unwrap was added as substitute for ko.utils.unwrapObservable

Homer
  • 7,594
  • 14
  • 69
  • 109
Ivan Rodriguez
  • 426
  • 4
  • 14