我有一个问题,当knockout.js从ajax调用设置一个可观察的数组时,我的动态html被重新填充。当发生这种情况时,动态HTML会重新加载,导致其中的init函数执行两次并重新绑定其他所有内容。为什么我的html observable会重新绑定动态HTML?我会使用Fiddle,但我有很多代码。
Ajax回调
app.viewModel.members.bracket.parts(response.Parts);
ko.applyBindings(app.viewModel.members, app.viewModel.members.container().find('> div:first').get(0));
容器
<div id="container" class="clearfix" data-bind="html: members.html, container: {}">
</div>
<script type="text/javascript">
app.viewModel.members = {
container: ko.observable($('#container')),
html: ko.observable(''),
bracket: {
parts: ko.observableArray([])
}
};
</script>
动态HTML
<div data-bind="with: members.bracket">
<div>
<div id="bracket-wrapper">
<div data-bind="template: { name: partTemplate, foreach: parts }"></div>
</div>
</div>
</div>
<script type="text/html" id="part-template-1">
<div class="bracket-part" data-bind="bracketGameInit: { left: $data.left, top: $data.top, height: $data.height, width: $data.width }, css: { 'reverse-bracket' : $data.reverse }"></div>
</script>
app.members.bracket.init({
pools: @Html.Raw(Model.DivisionPools.ToJSON()),
teams: @Html.Raw(Model.DivisionTeams.ToJSON()),
parts: @Html.Raw(Model.Parts.ToJSON())
});
答案 0 :(得分:0)
这是由我收到的Observable Array Performance小费引起的。我将它更新回更新可观察数组的旧方法。
function populateGameNumbers(gameNumbers) {
viewModel.gameNumbers([]);
var numbers = [];
for (var i = 0; i < gameNumbers; i++) {
numbers.push(i + 1);
}
viewModel.gameNumbers(numbers);
//viewModel.gameNumbers.push.apply(viewModel.gameNumbers, numbers );
}