确定对象属性是否为 ko.observable [英] Determine if an object property is ko.observable

查看:25
本文介绍了确定对象属性是否为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆