error:You cannot apply bindings multiple times to the same element解決


ko.applyBindings可接受兩個參數:

  1.第一個參數必寫,即我們創建的View Model

  2.第二個參數可選,表示第一個參數viewModel綁定的HTML范圍。默認為document。

參考:https://www.xiaoboy.com/detail/2015013117.html

You cannot apply bindings multiple times to the same element。這個問題是因為第二個參數有問題。

 

我現在想要做一個從主的viewmodel中分離出一個子viewmodel的例子。

  1.子viewmodel的數據由主viewmodel提供。

  2.但是子的viewmodel中,網頁數據改變,只會改變這個子的,不會改變主的數據。從而實現獨立分離出來

分離子model主要思想:將自己寫的子viemodel變成字符串,再eval解析出來,就算執行了。然后html的代碼也是先變成字符串,然后再用dom元素的innerHtml方式添加到自己的網頁上

把html,js轉成字符串,可以用這個網頁:http://www.css88.com/tool/html2js/

代碼:

1     <div id="Box">
2     <input data-bind="value:Name"/>
3     </div>
4     <div id="Content"><%--<input data-bind="value:YourName"/><span data-bind="text:YourName"></span>--%></div>
 1     <script type="text/javascript">
 2         require(['sysVM'], function (sysVM) {
 3             function AdminViewModel() {
 4                 var self = this;
 5                 self.Name = ko.observable("cat66");
 6 
 7                 //function TemplateViewModel() {
 8                 //    var that = this;
 9                 //    that.YourName = ko.observable(self.Name());
10                 //}
11                 var viewModelStr = "function TemplateViewModel() {" +
12 "                    var that = this;" +
13 "                    that.YourName = ko.observable(self.Name());" +
14 "                }";
15                 var htmlStr = "<input data-bind=\"value:YourName\"/><span data-bind=\"text:YourName\"></span>";
16                 eval(viewModelStr);
17                 var vm1 = new TemplateViewModel();
18                 var div = document.getElementById("Content");
19                 div.innerHTML = htmlStr;
20                 ko.cleanNode(div);
21                 ko.applyBindings(vm1, div);//綁定模板數據
22             }
23             
24             ko.applyBindings(new AdminViewModel(),document.getElementById("Box"));//綁定管理數據
25         });
26     </script>

如果最后管理數據綁定那里第二個參數不寫的話,表示document文檔,就會出錯,提示:You cannot apply bindings multiple times to the same element

我的理解是:每個ko.applyBindings都是單獨的綁定,應該讓它們都綁定到對應的dom元素上。不然可能會重復綁定在同一個元素上。

 

附:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM