我刚刚升级到Knockout.js 2.3.0,现在收到这个错误:
You cannot apply bindings multiple times to the same element.
这是我在2.2.1中没有得到的。
我从我的MVC控制器中获得了一个局部视图,并在单击href
后将其添加到页面。当我第二次单击该链接以获取局部视图时,出现了错误。我已经做了很多次了。
有没有办法解决这个问题并避免抛出新的错误?
下面是我的代码:
$.get(url + "GetAssignedCompaniesView?layoutId=" + layoutId + "&noCache=" + new Date().getMilliseconds(), function (result) {
$("#editAssignedPartial").html($(result));
showEditAssignedArea(true);
$(window.document).ready(function () {
// error is thrown here
ko.applyBindings(self, window.document.getElementById("editAssigned"));
$("#layoutId").attr("value", layoutId);
updateTypeHiddenElement.attr("value", "companies");
});
});
这是我的HTML:
<div id="area1">
<!-- grid here with links -->
</div>
<div id="editAssignedPartial"></div>
$(document).ready(function () {
'use strict';
var vm = new Vm();
ko.applyBindings(vm, document.getElementById("area1"));
});
发布于 2013-07-18 06:57:24
在再次使用applyBindings
之前,您需要删除绑定:
ko.cleanNode($element[0]);
发布于 2015-03-05 16:29:51
下面是抛出此异常的可能发生的事情。假设你有:
ko.applyBindings(myViewModel1, document.getElementById('element1'));
...
ko.applyBindings(myViewModel2, document.getElementById('element2'));
现在,当#element1
和#element2
都不存在时,你会得到错误。原因是当找不到#element1
和#element2
时,Knockout的applyBindings
依赖于document.body
作为根元素。现在它尝试在body上应用绑定两次...
如果你问我,这可不是一个很好的淘汰赛。我更希望有一个明确的错误消息,该元素不存在于DOM中(还没有)。
发布于 2013-07-18 06:35:01
永远不要将绑定多次应用于一个视图。在2.2中,该行为未定义,但仍未得到支持。在2.3中,它现在正确地显示了一个错误。使用knockout时,目标是将绑定应用于页面上的视图一次,然后使用对视图模型上的可观察对象的更改来更改页面上视图的外观和行为。
https://stackoverflow.com/questions/17710788
复制相似问题