我正在使用kendo移动应用程序构建器,我正在使用knockout js进行绑定但我收到错误" 您无法多次将绑定应用于同一元素"。我有两个javascript文件,包含绑定,在我的代码下面
//Employee.js//
function EmployeeViewModel() {
this.EmployeeName= ko.observable();
this.EmployeeMobile= ko.observable();
this.EmployeeEmail= ko.observable(); }
ko.applyBindings(new EmployeeViewModel());
//Company.js//
function CompanyViewModel() {
this.CompanyName= ko.observable();
this.CompanyMobile= ko.observable();
this.CompanyEmail= ko.observable(); }
ko.applyBindings(new CompanyViewModel());
//In index page i am using this both script file drag and drop//
<html>
<head>
</head>
<body>
<script src="Employee.js"></script>
<script src="Company.js"></script>
</body>
</html>
答案 0 :(得分:15)
&#34; ko.applyBindings&#34;函数有两个参数:
applyBindings(viewModelOrBindingContext, rootNode);
第一视图模型
第二 - DOM节点将绑定应用于
你打电话给&#34; ko.applyBindings&#34;方法两次 - 在两个函数中,仅使用第一个参数。这意味着您要将两个不同的模型绑定到同一节点 - 文档根目录。这会导致错误。
您可以使用两种方法:
使用子模型创建一个全局视图模型,并仅应用绑定一次:
//Employee.js//
function EmployeeViewModel() {
this.EmployeeName= ko.observable();
this.EmployeeMobile= ko.observable();
this.EmployeeEmail= ko.observable();
}
//Company.js//
function CompanyViewModel() {
this.CompanyName= ko.observable();
this.CompanyMobile= ko.observable();
this.CompanyEmail= ko.observable();
}
//In index page i am using this both script file drag and drop//
<html>
<head>
</head>
<body>
<script src="Employee.js"></script>
<script src="Company.js"></script>
<script>
ko.applyBindings({ employee: new EmployeeViewModel(), company: new CompanyViewModel() });
</script>
</body>
</html>
将绑定应用于不同的节点:
```
//Employee.js
function EmployeeViewModel() {
this.EmployeeName= ko.observable();
this.EmployeeMobile= ko.observable();
this.EmployeeEmail= ko.observable();
ko.applyBindings(new EmployeeViewModel(), document.getElementById("employee"));
}
//Company.js
function CompanyViewModel() {
this.CompanyName= ko.observable();
this.CompanyMobile= ko.observable();
this.CompanyEmail= ko.observable();
ko.applyBindings(new CompanyViewModel(), document.getElementById("company"));
}
//In index page i am using this both script file drag and drop//
<html>
<body>
<script src="Employee.js"></script>
<script src="Company.js"></script>
<div id="employee"></div>
<div id="company"></div>
</body>
</html>
```
答案 1 :(得分:1)
多次应用绑定。您需要先清除绑定。
如下所示
var element = $('#elementId')[0];
ko.cleanNode(element);
然后只有你可以在同一个元素上再次应用绑定。