我是否需要在嵌套的for循环中使用闭包?

时间:2019-02-21 16:01:19

标签: javascript knockout.js

如何确保我的数据放在正确的位置?

我在使用KnockoutJS foreach,但是在HTML中仅使用一个foreach,而不是嵌套的:

<tbody data-bind="foreach: locationsFilteredYears">
        <tr>  
             <td data-bind="text: Month"></td>
         </tr>    
         <tr>  
             <td data-bind="text: Title"></td>
         </tr>    
</tbody>  

控制器:

var j: any;
      for(i=0;i<filteredEvents.length;i++){
        for(j=0+i;j<months.length;j++){
          if(months[j].value,filteredEvents[i].StartDate.substring(3, 5)){
            filteredEvents[i].Month = months[j].name;
            console.log(months[j].name);
            console.log(months[i].name);
          }
        }
      }

//push to view
this.locationsFilteredYears(filteredEvents);

结果: Result

预期: enter image description here

1 个答案:

答案 0 :(得分:0)

在前端迷路了,并且如上所述,我的评论仍然没有完全掌握Observables和MVVM的方式...我最终没有使用不使用Knockout绑定,现在的工作版本如下:

//Manually Create months
var mTblRowJan = '';
    var mTblRowFeb = '';
    var mTblRowMar = '';
    var mTblRowApr = '';
    ...

//Filter through array of api data
filteredEvents.forEach((a) => {

//pull out data month by month
//I.e. for jan it's
     if(a["Start_x0020_Date"].indexOf('-01-') > -1){
          mTblRowJan += `<tr><td>`+a.Title+`</td><td>`+this.formatDate(a["Start_x0020_Date"].toString())+`</td><td>`+this.formatDate(a["End_x0020_Date"].toString())+`</td><td><a href='https://web.powerapps.com/apps/?event_id='`+a.Id+`'>Book</a></td></tr>`;
                  console.log(a["Start_x0020_Date"].toString(), a.Title);
        }
});

//Build table manually in backend with manually created Months labels for seperation
//and add dynamic row
//this can contain as many tables rows as needed for any given month
 var mTbl = `<table class="table">
          <thead>
            <tr>
              <th scope="col">Title</th>
              <th scope="col">Start Date</th>
              <th scope="col">End Date</th>
              <th scope="col">Booking</th>
            </tr>
          </thead>
          <tbody>
                  <tr><td><h4>JANUARY</h4> </td></tr>  
                  ` +mTblRowJan+ `      
          </tbody>
        </table>`;

//push table to view
this.tblTest(mTbl);


//As you can see not using Knockout and it's a just a dynamic JS table so any advice on how to turn this version to use nested data-binds in front end would be helpful!