简体   繁体   English

Knockout.js和分块实用程序

[英]knockout.js and chunking utility

Id like to create some sort of function that will chunk an array into a certain amount and display those in a row. 我想创建某种函数,该函数会将数组分块成一定数量并连续显示。 Below I have an array called pools that would show all pools. 在下面,我有一个称为池的数组,它将显示所有池。 Id like to show three per row though. 我想每行显示三个。 The javascript function below works in code, but how would you do this with knockout.js? 下面的javascript函数可在代码中使用,但是如何使用敲除(snockout.js)?

HTML 的HTML

<!-- ko foreach: pools -->

Javascript Java脚本

var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);

}

You could create an array of objects where each object contains an array of the actual items in your "array" and then a nested loop in ko. 您可以创建一个对象数组,其中每个对象都包含“数组”中实际项目的数组,然后是ko中的嵌套循环。

 var i, j, tempArray = [], chunk = 10;
 for (i=0,j=array.length, k=0; i<j; i+=chunk, k++) {
    temparray[k] = { items: array.slice(i,i+chunk); }
 }

HTML 的HTML

  `<!-- ko foreach: pools -->
      <div class="row">
      <!-- ko foreach: items -->
           <div class="col">`

Assuming pools is an observable containing your data, you can make a poolRows computed that calculates based on pools : 假设pools是可观察的包含您的数据的数据,则可以使poolRows计算出基于pools计算:

var pools = ko.observableArray([]);

var poolRows = ko.computed(function () {
    var poolRows = [];
    for(var i=0;i<pools().length;i++) {
        var pool = pools()[i];
        if(i % 3 === 0) {
            poolRows.push([]);
        }
        poolRows[Math.floor(i/3)].push(pool);
    }
    return poolRows
});

Then: 然后:

<!-- ko foreach: {data: poolRows, as: 'poolRow'} -->
    <!-- ko foreach: {data: poolRow, as: 'pool'} -->
         <!-- pool html here -->
    <!-- /ko -->
<!-- /ko -->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM