确定一个对象属性是否是可观察的

我使用的是 帅哥2.0版

如果循环遍历对象的所有属性,那么如何测试每个属性是否是 ko.observable?以下是我目前为止的尝试:

    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);
}

但到目前为止,一切都是假的。

49367 次浏览

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.

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

ko.isObservable(vm[key])

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

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.