如何检查对象在knockout js中有任何属性

时间:2015-06-25 11:42:31

标签: javascript object knockout.js

如何检查可淘汰对象是否在淘汰赛中存在属性 我尝试过使用hasOwnProperty并且总是向我返回错误。

我的代码如下:

    <div data-bind="click:setObject">Click here</div>
    <div data-bind="click:init">check console</div>
    <script>
        var ViewModel = function() {
            var self = this;
            this.arrayVal = ko.observable({});
            this.setObject = function(){  /* i have set property here  */
                self.arrayVal({
                    id:10
                });
            };
            self.init = function(){
                console.log(self.arrayVal());
                console.log(self.arrayVal.hasOwnProperty('id'));  /* on second click (after setObject ) i expect trut,but it returned false */
            }
            self.init();
        };
        ko.applyBindings(new ViewModel()); 
    </script>

1 个答案:

答案 0 :(得分:4)

您需要获取arrayVal observable中的值:

console.log(self.arrayVal().hasOwnProperty('id'));

observable本身有方法hasOwnProperty但不是属性id,因此

self.arrayVal.hasOwnProperty('id');    // false, 'id' doesn't exist on the observable

,而

self.arrayVal().hasOwnProperty('id');    // true, 'id' exists on the observable's value