Apply a class to every nth template element with knockoutjs

强颜欢笑 提交于 2020-01-03 06:31:12

问题


I've been experimenting with knockoutjs, reworking an existing project.

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?


回答1:


A few options for you:

  • there is work being done to add a $index variable when doing a foreach in KO. This is scheduled to be included in KO 2.1. The pull request is here: https://github.com/SteveSanderson/knockout/pull/182

  • there is a repeat binding here: https://github.com/mbest/knockout-repeat that gives you better access to the actual index.

  • if you are using an observableArray, then there is an easy way to create an index each item.

It would look like this:

//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;
};

You would initialize an observableArray to be indexed like:

this.myArray = ko.observableArray().indexed();

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.



来源:https://stackoverflow.com/questions/9760861/apply-a-class-to-every-nth-template-element-with-knockoutjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!