确定对象属性是否为ko.observable [英] Determine if an object property is ko.observable
问题描述
我正在使用 KnockoutJS 版本2.0.0
I'm using KnockoutJS version 2.0.0
如果我循环遍历对象的所有属性,我如何测试每个属性是否为 ko.observable
?这是我到目前为止所尝试的:
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.
推荐答案
Knockout包含一个名为 ko.isObservable()
的函数。您可以像 ko.isObservable(vm [key])
一样调用它。
Knockout includes a function called ko.isObservable()
. You can call it like ko.isObservable(vm[key])
.
评论更新:
这是一个确定某些东西是否是计算出的可观测量的函数:
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
};
更新:如果您使用的是KO 2.1+ - 那么您可以使用 ko .isComputed
直接。
UPDATE: If you are using KO 2.1+ - then you can use ko.isComputed
directly.
这篇关于确定对象属性是否为ko.observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!