Javascript Knockoutjs将biding应用于多个html节点
我在一个页面上运行多个视图模型,为了修复任何潜在的冲突,我将父html节点添加到了knockout apply bindings文本中。然而,我遇到的一个问题是,我不能再使用这些节点之外的属性。我试图找出是否有任何方法可以更新视图模型绑定之外的单个html节点,我也绑定了该模型Javascript Knockoutjs将biding应用于多个html节点,javascript,html,knockout.js,Javascript,Html,Knockout.js,我在一个页面上运行多个视图模型,为了修复任何潜在的冲突,我将父html节点添加到了knockout apply bindings文本中。然而,我遇到的一个问题是,我不能再使用这些节点之外的属性。我试图找出是否有任何方法可以更新视图模型绑定之外的单个html节点,我也绑定了该模型 <html> <head> <script> function VM1() { this.ViewModelProp1 = ko.obs
<html>
<head>
<script>
function VM1() {
this.ViewModelProp1 = ko.observable(1);
this.NotficationsNumber = ko.observable(1);
}
function VM2() {
this.ViewModelProp2 = ko.observable(1);
}
ko.applyBindings(VM1, document.getElementById('vm1'));
ko.applyBindings(VM1, document.getElementById('vm2'));
</script>
</head>
<body>
<!-- I want this property applied to the VM1 -->
<h1 id="notifiy" data-bind="text: NotficationsNumber"></h1>
<p id="vm1">
<strong data-bind="text: ViewModelProp1"></strong>
</p>
<p id="vm2">
<strong data-bind="text: ViewModelProp2"></strong>
</p>
</body>
</html>
函数VM1(){
this.ViewModelProp1=ko.可观察(1);
本条说明编号=可观察的ko(1);
}
函数VM2(){
this.ViewModelProp2=ko.可观察(1);
}
ko.applyBindings(VM1,document.getElementById('VM1'));
应用绑定(VM1,document.getElementById('vm2');
只要把它放在自己的容器里就行了
<html>
<head>
<script>
function VM1() {
this.ViewModelProp1 = ko.observable(1);
this.NotficationsNumber = ko.observable(1);
}
function VM2() {
this.ViewModelProp2 = ko.observable(1);
}
ko.applyBindings(VM1, document.getElementById('div1'));
ko.applyBindings(VM1, document.getElementById('vm2'));
</script>
</head>
<body>
<!-- I want this property applied to the VM1 -->
<div id='div1'>
<h1 id="notifiy" data-bind="text: NotficationsNumber"></h1>
<p id="vm1">
<strong data-bind="text: ViewModelProp1"></strong>
</p>
</div>
<p id="vm2">
<strong data-bind="text: ViewModelProp2"></strong>
</p>
</body>
</html>
函数VM1(){
this.ViewModelProp1=ko.可观察(1);
本条说明编号=可观察的ko(1);
}
函数VM2(){
this.ViewModelProp2=ko.可观察(1);
}
应用绑定(VM1,document.getElementById('div1');
应用绑定(VM1,document.getElementById('vm2');
您可以在多个位置绑定同一视图模型,即只需添加
ko.applyBindings(VM1, document.getElementById('notify'));
顺便说一句,您的HTML中有“notifiy:)您可以在DOM中的每个节点中应用绑定,但您需要的是更改另一个绑定在DOM中的viewModel,对吗?因此,您可以使用
ko.dataFor(element)
将视图模型绑定到元素中,请参见代码段:
请参见代码片段:
注:这是解决该问题的方法之一
函数VM1(){
this.ViewModelProp1=ko.observable(“VM 1”);
此.notificationsNumber=ko.可观察(“VM 1”);
}
函数VM2(){
this.ViewModelProp2=ko.可观察(“vm2”);
}
函数更新程序(){
this.textUpdate=ko.可观察(“更新”);
this.textUpdate.subscribe(函数(nvalue){
var vm1=ko.dataFor(document.getElementById('div1');
vm1[“ViewModelProp1”](nvalue);
},这个);
};
applyBindings(newupdater(),document.getElementById('updater');
ko.applyBindings(newVM1(),document.getElementById('div1');
ko.applyBindings(newVM2(),document.getElementById('VM2')代码>
只需创建一个稍微复杂一点的ViewModel。你能解决这个问题吗?请阅读答案