javascript – Knockout Js“你不能多次将绑定应用于同一个元素”

前端之家收集整理的这篇文章主要介绍了javascript – Knockout Js“你不能多次将绑定应用于同一个元素”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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>

解决方法

“ko.applyBindings”函数有两个参数:
applyBindings(viewmodelOrBindingContext,rootNode);

第一视图模型

second – 将应用绑定的DOM节点

在两个函数中,只使用第一个参数调用“ko.applyBindings”方法两次.这意味着您要将两个不同的模型绑定到同一节点 – 文档根目录.这会导致错误.

您可以使用两种方法

>使用子模型创建一个全局视图模型并仅应用绑定一次:

//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>

“`

猜你在找的JavaScript相关文章