Knockout js将多个可观察对象组合在一起

时间:2013-02-27 21:00:38

标签: javascript knockout.js

我想知道是否有任何方法可以使用单个对象更新整个viewmodel 例如,说我们的viewmodel如下:

    Function ExampleViewModel(){
     this.name = ko.observable();
     this.lastname = ko.observable();
     this.phone = ko.observable();
    }
    var viewmodel = new ViewModel();
    ko.applyBindinings(viewmodel);

然后假设我创建了一个对象:

    var newObject = {name: "newname", lastname: "lastname", phone: 432}

而不是按如下方式单独设置每个可观察量:

        viewmodel.name(newObject.name);
             or
        viewmodel.name(newObject.name).lastname(newObject.lastname) etc etc

我可以更新整个viewmodel,例如:

        viewmodel.update(newObject)?

1 个答案:

答案 0 :(得分:1)

只需遍历对象:

for (var key in newObject) {
    if (viewModel[key] && ko.isObservable(viewModel[key])) {
        viewModel[key](newObject[key]);
    }
}