这是我的观点:
@model Horeko.Web.ViewModels.MyUpdateViewModel
<div id="main">
<div>
more nested divs with data bindings
<div id="importDiv" data-bind="stopBinding: true">@Html.Partial("MyPartialView", Model.ImportSettings)</div>
</div>
</div>
js中的代码如下所示:
var myInfoModel = function (model) {
var self = this;
var mapping = {
'include': ["desc", "name", "start", "end", "importSettings"],
'copy': ["id"]
};
ko.mapping.fromJS(model, mapping, self);
}
var infoModel = new myInfoModel(model);//model is from the view
var infoPanel = $("main")[0];
ko.applyBindings(infoModel, infoPanel);
ko.cleanNode(infoModel.importSettings, $("#importDiv")[0]);
ko.applyBindings(infoModel.importSettings, $("#importDiv")[0]);
我想在此处将importDiv排除在绑定之外,并将其与另一个infoModel.importSettings绑定。所以就像我对主要&#39;那样做。上面的div,但是对于&#39; import&#39; DIV。但是我无法做到这一点,因为我收到错误&#39;您无法多次将绑定应用于同一元素&#39;。
答案 0 :(得分:0)
cleanNode方法的问题在于绑定最初仍会附加一次,因此它们和该节点内的任何其他绑定都必须解析而不会出错。
为了解决这个问题,您可以摆脱第二个“applyBindings”并使用带有可观察布尔值的“if”绑定来告诉绑定何时渲染内部div。
var myInfoModel = function () {
var self = this;
self.ready = ko.observable(false);
setTimeout(function(){
self.info = 'Inner Bindings';
self.ready(true);
}, 1000);
}
var infoModel = new myInfoModel();//model is from the view
var infoPanel = $("#main")[0];
ko.applyBindings(infoModel, infoPanel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="main">
<div>
<span>Outer Binding</span>
<div data-bind="if: ready">
<div id="importDiv">
<span data-bind="text: info"></span>
</div>
</div>
</div>
</div>
如果这对您的场景不起作用,您可以在调用applyBindings之前从DOM中删除内部div,然后在准备绑定它之后重新附加它。
var myInfoModel = function () {
var self = this;
self.importSettings = { info: 'Inner Bindings' };
}
var infoModel = new myInfoModel();//model is from the view
var infoPanel = $("#main")[0];
var $importPanel = $("#importDiv").detach();
ko.applyBindings(infoModel, infoPanel);
setTimeout(function(){
$importPanel.appendTo("#main");
ko.applyBindings(infoModel.importSettings, $("#importDiv")[0]);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="main">
<div>
<span>Outer Binding</span>
<div id="importDiv">
<span data-bind="text: info"></span>
</div>
</div>
</div>