我使用 Knockout 映射插件每 3 秒使用从服务器检索的 JSON 刷新 UI。UI 由一些嵌套foreach
绑定组成。但是,似乎所有foreach
绑定中的所有内容都被完全删除并在每次刷新时重新渲染,即使没有任何变化。
var testData = {
Answers: [],
Inspectable: {
Categories: [{
Id: 1,
Name: "Test Category",
Questions: [{
Id: 1,
Text: "Test Question",
Active: true,
Answers: [{
Text: "Test Answer",
Id: 1
}]
}]
}]
}
};
function ViewModel() {
var self = this;
this.refreshUrl = $("[data-view=edit]").data("url");
this.refresh = function(callback) {
$.get(self.refreshUrl, function(data) {
//Ignoring actual JSON data for testing
ko.mapping.fromJS(testData, {}, self);
if (typeof callback == "function") {
callback.call(self);
}
});
}
this.addedQuestion = function() {
// Gets called for every question every refresh by afterRender
// Never gets called at all by afterAdd
}
};
var refreshing = false, handler;
window.viewModel = new ViewModel();
//Initialize the UI after initial AJAX is completed
viewModel.refresh(function() {
ko.applyBindings(this);
$(document).on("click", ".add-question", function() {
if (!refreshing) {
handler = setInterval(viewModel.refresh, 3000);
refreshing = true;
}
});
});
有没有人认为这有什么明显的错误?
编辑
我编辑了脚本以使用静态 JavaScript 对象。它仍然重新渲染每次刷新。还更新到淘汰赛 2.3.0。这是视图:
<!-- ko foreach: Inspectable.Categories -->
<div class="row row-fluid space-above">
<h4 class="orange" data-bind="text: Name"></h4>
<!-- ko foreach: { data: Questions, afterRender: $root.addedQuestion } -->
<!-- ko if: Active() || ~$.map($root.Answers(), function(a) { return a.Id() == Id() }) -->
<div class="question space-above">
<p><strong data-bind="text: Text"></strong></p>
<div class="answers" data-bind="foreach: Answers">
<!-- ko if: $parent.AllowMultiple --><label class="checkbox"><input type="checkbox" data-url="<%= Url.Action("AddOrRemoveAnswer") %>" data-bind="attr: { value: Id, name: 'question-' + $parent.Id() }"/><!-- ko text: Text --><!-- /ko --></label><!-- /ko -->
<!-- ko ifnot: $parent.AllowMultiple --><label class="radio"><input type="radio" data-url="<%= Url.Action("AddOrRemoveAnswer") %>" data-bind="attr: { value: Id, name: 'question-' + $parent.Id() }"/><!-- ko text: Text --><!-- /ko --></label><!-- /ko -->
</div>
</div>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: Questions().length == 0 -->
<div class="question space-above">
<p><strong>No questions in this category.</strong> <a class="add-question" data-bind="attr: { href: '<%= Url.Action("Create", "Questions") %>?categoryId=' + Id() + '&inProgress=true' }" target="_blank">Add some.</a> </p>
</div>
<!-- /ko -->
<!-- ko if: Questions().length > 0 -->
<div class="question space-above">
<a class="add-question" data-bind="text: 'New question for ' + Name(), attr: { href: '<%= Url.Action("Create", "Questions") %>?categoryId=' + Id() + '&inProgress=true' }" target="_blank"></a>
</div>
<!-- /ko -->
</div>
<!-- /ko -->