简体   繁体   中英

How to create a table with random data in Ember.Js

I want to create a random table data but only cells makes random the rows always repeated. Here is my code:

component/ember-app..js

    import Ember from 'ember';

export default Ember.Component.extend({
  willRender: function() {
    var tableRows = [];
    var value = ['|', '-'];
    var numRows = 20;
    var numCells = 20;
    for (var row = 1; row <= numRows; row++) {
      for (var cell = 1; cell <= numCells; cell++) {
        tableRows[row] = value[Math.round(Math.random())];
      }
    }

    this.set('rows', {
      'tableRows': tableRows,
    });

  }
});

And templates/components/ember-app.hbs

  <table>
{{#each-in rows as |table tableRow|}}
{{#each tableRow}}
  <tr>
      {{#each tableRow as |tableRows|}}
      <td><button id="button_id"{{action "changeValue"}} value="{{tableRows}}">{{tableRows}}</button></td>
      {{/each}}
  </tr>
  {{/each}}
  {{/each-in}}
</table>

You are not creating different cells values for each row,

Component.js

export default Ember.Component.extend({
  willRender: function() {
    var tableRows = [];
    var value = ['|', '-'];
    var numRows = 20;
    var numCells = 20;
    for (var row = 1; row <= numRows; row++) {
      var cellArr = []
      for (var cell = 1; cell <= numCells; cell++) {
        console.log('Math.round(Math.random()) ',Math.round(Math.random()));
        cellArr[cell] = value[Math.round(Math.random())];
      }
      tableRows[row]=cellArr;
    }

    this.set('rows', {
      'tableRows': tableRows,
    });

  }
});

in component hbs,

<table>
{{#each-in rows as |table tableRow|}}
{{log 'tableRow ' tableRow ' table ' table}}
{{#each tableRow as |singleRow|}}
  <tr>
      {{#each singleRow as |tableRows|}}
      <td><button id="button_id"{{action "changeValue"}} value="{{tableRows}}">{{tableRows}}</button></td>
      {{/each}}
  </tr>
  {{/each}}
  {{/each-in}}
</table>
{{yield}}

I would suggest you consider, Ember.Object and use init hook to init data. ember-twiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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