I am using kendo mobile app builder and I am using knockout js for bindings but I am getting error "You cannot apply bindings multiple times to the same element". I have two javascript file which consist bindings, below my code
//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>
The "ko.applyBindings" function takes 2 arguments:
applyBindings(viewModelOrBindingContext, rootNode);
first - view model
second - DOM node the binding will be applied to
You call "ko.applyBindings" method twice - in both functions, with the first parameter only. This means you are going to bind two different models to the same node - document root. This causes the error.
You can use two approaches:
create one global view model with submodels and apply binding only once:
//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>
apply bindings to different nodes:
```
//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>
```
To apply binding multiple time. You need to first clear the binding.
like below
var element = $('#elementId')[0];
ko.cleanNode(element);
Then only you can apply binding again on same element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With