循环遍历具有knockout可观察属性的JS对象

时间:2014-06-17 08:53:54

标签: javascript knockout.js javascript-objects

我有以下JS对象:

function AdvancedFilters() {
    var self = this;
    self.AdvancedColId = ko.observable();
    self.AdvancedComapanyName = ko.observable();
    self.AdvancedClientCountry = ko.observable();
    self.AdvancedClientCity = ko.observable();
    self.AdvancedDatabaseLocation = ko.observable();
    self.AdvancedUserName = ko.observable();
    self.AdvancedEmail = ko.observable();
    self.AdvancedPhoneNo = ko.observable();
    self.AdvancedAccessFrom = ko.observable();
    self.AdvancedAccessTo = ko.observable();
    self.AdvancedCreatedOn = ko.observable();
    self.AdvancedCandidates = ko.observable();
    self.AdvancedErrorsReported = ko.observable();
    self.AdvancedActive = ko.observable();
    self.AdvancedRequestes = ko.observable();
}

我必须循环遍历AdvancedFilters对象中存在的所有属性,并执行适用于所有属性的操作,而不是分别访问每个属性。我必须这样:

for (var property in AdvancedFilters) {         
         // do something with property     
}

我尝试了上面的语法,但它没有用。

1 个答案:

答案 0 :(得分:6)

试试这个

function AdvancedFilters() {
    var self = this;
    self.AdvancedColId = ko.observable();
    //...
}

var obj = new AdvancedFilters();
for (var property in obj) {         
    alert(ko.isObservable(obj[property]) ? obj[property]() : property);
}