iam unable to applybindings in knockout 这是正确的方法吗?

iam unable to applybindings in knockout is this correct approach?

我有两个视图模型,我想要应用绑定,一个视图模型是 Div 特定的,另一个是整页

var profileModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith")
 };

var shellModel = {
header: ko.observable("Administration"),
sections: ["profile", "settings", "notifications"],
selectedSection: ko.observable()
};

 ko.applyBindings(shellModel);
 ko.applyBindings(profileModel, document.getElementById("profile"));

您不能调用 ko.applyBindings(...) 相同的父元素,甚至不能调用相同父元素中的子元素。

当您调用 ko.applyBindings(shellModel) 时,您将模型绑定到整个 DOM,稍后,您将在同一文档的子元素中启动其他绑定。

如果您想这样做,请将两个视图模型合并为一个并执行 ko.applyBindings(mergedModel) 它应该适用于您的方案。或者为 shellModel 调用 ko.applyBindings(...) 到不应成为 profile.

父级的具体元素

您好@Jairam,您可以创建一个具有两个视图模型的对象并将绑定应用于对象:

 var profileModel = {
    first: ko.observable("Bob"),
    last: ko.observable("Smith")
     };

    var shellModel = {
    header: ko.observable("Administration"),
    sections: ["profile", "settings", "notifications"],
    selectedSection: ko.observable()
    };

    var viewModel = {
      subModelA: profileModel ,
      subModelB: shellModel 
    };

    ko.applyBindings(viewModel);

您可以尝试这样的操作,它可以合并两个视图模型。有点像继承,viewmodel2继承了viewmodel1的所有属性。

function viewModel1() {
  var self = this;

  self.vm1Alert = function() {
    alert('Model 1 stuff')
  };
}


function viewModel2() {
  var self = this;

  viewModel1.call(self);
  self.vm1Alert(); //from the first viewmodel
  alert('Model 2 stuff');

}
ko.applyBindings(new viewModel2());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>