Determine if an object property is ko.observable

前端 未结 4 842
时光取名叫无心
时光取名叫无心 2020-12-24 11:17

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\

相关标签:
4条回答
  • 2020-12-24 11:49

    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

    0 讨论(0)
  • 2020-12-24 11:52

    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.

    0 讨论(0)
  • 2020-12-24 11:54

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

    ko.isObservable(vm[key])
    
    0 讨论(0)
  • 2020-12-24 11:57

    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.

    0 讨论(0)
提交回复
热议问题