Determine if an object property is ko.observable

Javascriptknockout.js

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

ko.isObservable(vm[key])

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam RackisView Question on Stackoverflow
Solution 1 - JavascriptRP NiemeyerView Answer on Stackoverflow
Solution 2 - JavascriptMark RobinsonView Answer on Stackoverflow
Solution 3 - JavascriptpimView Answer on Stackoverflow
Solution 4 - JavascriptIvan RodriguezView Answer on Stackoverflow