使用Knockout.js将类应用于每个第n个模板元素 [英] Apply a class to every nth template element with knockoutjs
问题描述
我一直在尝试 knockoutjs ,重新设计一个现有项目.
I've been experimenting with knockoutjs, reworking an existing project.
我当前的布局具有确定渲染的<div>
标签是第一项还是第四项的逻辑.
My current layout has the logic to determine if the rendered <div>
tag is the first or fourth item.
if (index % 4 == 0) addClass('omega');
if (index % 4 == 1) addClass('alpha');
是否有内置的敲除功能可以模拟相似的条件?
Is there any built-in functionality of knockout that can template similar conditions?
推荐答案
为您提供一些选择:
-
在KO中执行
foreach
时,正在做添加$index
变量的工作.计划将其包含在KO 2.1中.提取请求在此处: https://github.com/SteveSanderson/knockout/pull/182
there is work being done to add a
$index
variable when doing aforeach
in KO. This is scheduled to be included in KO 2.1. The pull request is here: https://github.com/SteveSanderson/knockout/pull/182
此处有repeat
绑定: https://github.com/mbest/淘汰赛重复,使您可以更好地访问实际索引.
there is a repeat
binding here: https://github.com/mbest/knockout-repeat that gives you better access to the actual index.
如果使用的是observableArray,则有一种简单的方法来为每个项目创建索引.
if you are using an observableArray, then there is an easy way to create an index each item.
它看起来像这样:
//track an index on items in an observableArray
ko.observableArray.fn.indexed = function() {
//whenever the array changes, make one loop to update the index on each
this.subscribe(function(newValue) {
if (newValue) {
var item;
for (var i = 0, j = newValue.length; i < j; i++) {
item = newValue[i];
if (!ko.isObservable(item.$index)) {
item.$index = ko.observable();
}
item.$index(i);
}
}
});
this.valueHasMutated();
return this;
};
您将初始化一个observableArray来进行索引,例如:
You would initialize an observableArray to be indexed like:
this.myArray = ko.observableArray().indexed();
现在,当操作可观察数组时,它将对项目进行一遍检查并更正索引.这比每次在foreach
内部查找每个项目的索引都要好.
Now, when the observable array is manipulated, it will take one pass through the items and correct the index. This is better than inside your foreach
looking up the index of each item each time.
这篇关于使用Knockout.js将类应用于每个第n个模板元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!