我有一些旧代码,我想看看是否可以使用 knockout.js。
var secs = 960 + Math.floor(data.length / 6) * 1060 + 10;
$("#metro-scrollbar").css("width", secs.toString() + 'px');
var group_count = 0;
section = ""
for (i = 0; i < data.length; i++) {
if (i % 6 == 0)
section += "<section class=\"" + (data.length - i <= 6 ? "last" : "") + "\"><h2 class=\"section-title\">Group " + ++group_count + "</h2>";
section += "<a href=\"/TheoryTests/Test/" + data[i].Id + "/" + data[i].Title.replace(/ /g,'-') + "\">";
section += "<div class=\"metro-tile double" + (i % 3 == 2 ? " last" : "") + "\"><div class=\"a1x2\"></div><div class=\"live-tile metrogreen\">";
section += "<span class=\"tile-title\">" + data[i].Title + "</span>";
section += "<div class=\"dark\"><div class=\"TheoryTestTile\"><p>Helo</p></div></div>";
section += "</div></div></a>";
if (i % 6 == 5)
section += "</section>";
}
javascript 生成了一组带有一些嵌套 div 的部分。每 6 个 div 它创建一个新部分。我了解如何使用 knockout.js 进行数据绑定
data-bind="foreach: test, visible: tests().length > 0" 但是如果(i%6 == 0)我该如何做决策
更新
<div id="metro-grid">
<div id="metro-scrollbar" data-bind="foreach: tests, visible: tests().length > 0">
<!-- ko if: $index() % 6 == 0 -->
<section data-bind ="css: { 'last' : $parent.isLastSection($index)}," >
<!-- /ko -->
<div class="metro-tile double " data-bind ="css: { 'last' : $parent.isLastTile($index)}">
<div class="a1x2"></div><div class="live-tile metrogreen">
<div ></div>
</div>
</div>
<!-- ko if: $index() % 6 == 0 -->
</section>
<!-- /ko -->
</div>
</div>
上面的问题是我仍然想在 section 中生成 div。tests 是一个包含 12 个元素的列表。我想每个第 6 个元素创建一个新部分。
更新 2
function TaskListViewModel() {
// Data
var self = this;
self.tests = ko.observableArray([]);
this.sections = [];
self.isLastTile = function (i) {
return i() % 3 == 2;
};
self.isLastSection = function (i) {
return i() >= Math.floor(self.tests().length / 6);
};
this.createSections = ko.computed(function () {
var tests = self.tests();
current = [];
sections.push(current);
for (var i = 0; i < tests.length; i++) {
current.push(tests[i]);
if (((i+1) % 6) == 0) {
current = [];
sections.push(current);
}
}
});
$.getJSON(url, function (allData) {
var mappedTasks = $.map(allData, function (item) { return new Task(item) });
self.tests(mappedTasks);
//var secs1 = self.tests().length / 6 * 960 + 960 + 10;
var secs = 960 + Math.floor(self.tests().length / 6) * 1060 + 10;
$("#metro-scrollbar").css("width", secs.toString() + 'px');
});
}
ko.applyBindings(new TaskListViewModel());