从组件模板中访问Ember组件数据

时间:2016-08-29 18:44:06

标签: javascript jquery ember.js

我正在试图找出Ember.js,这样我就不会手动操作DOM,而是使用把手代替。

我正在尝试访问组件模板中的组件数据,以便我可以迭代数据并构建表。如果这不是Ember方式,请告诉我。我没有模型,商店或路线中的数据集。一切都在“问题数据”组件中完成。

以下是组件及其模板:

import Ember from 'ember';

export
default Ember.Component.extend({
  runAll: null,
  csvData: null,
  initTable: function() {
    function buildTable() {
      var csvFile;
      Ember.$.ajax({
        url: 'open_issues_data/open_issues_data.csv',
        dataType: 'text',
        async: false,
        success: function(response) {
          csvFile = response;
        },
        error: function(err) {
          console.log(err);
        }
      });

      Papa.parse(csvFile, {
        complete: function(results) {
          csvFile = results.data;
          this.csvData = csvFile;
        }
      });

      /* Uncomment when ready to implement filter
        options = {
          valueNames: ["issue_number", "customer_id", "date_reported", "location"]
        };

        var myList = new List("table-div", options);
      */
    }
    buildTable();
  }.on('didInsertElement'),

  didInsertElement() {
    this.runAll = Ember.run.later(this, function() {
      this.initTable();
      this.runAll = Ember.run.later(this, this.runAll, 60000);
    }, 60000);
  },

  didDestroyElement() {
    Ember.run.cancel(this.runAll);
  }
});
<div id="table-div">
  <input class="search" placeholder="Filter by your input">
  <button class="sort" data-sort="issue_number">Sort by Issue #</button>
  <table id='data-table' class='table table-striped table-bordered'>
    <tbody id='table-body' class="list">
      {{#each row in issue-data.csvData}}
      <tr>
        {{#each column in row}}
        <td>{{column}}</td>
        {{/each}}
      </tr>
      {{/each}}
    </tbody>
  </table>
</div>

{{yield}}

以下是路线的模板:

<h2>Open Issues Data</h2>
{{issue-data}}

{{outlet}}

1 个答案:

答案 0 :(得分:-1)

在挖掘文档时想出来:https://guides.emberjs.com/v2.7.0/models/

有一种更好的方法,但是Ember自己的文档说你可以使用this.set()为数据分配一个键。为了得到正确的“this”,我通过使用一个新变量来保持范围:

var _component = this;
var csvFile;
Ember.$.ajax({
  url: 'open_issues_data/open_issues_data.csv',
  dataType: 'text',
  async: false,
  success: function(response) {
    csvFile = response;
  },
  error: function(err) {
    console.log(err);
  }
});

Papa.parse(csvFile, {
  complete: function(results) {
    csvFile = results.data;
    this.csvData = csvFile;
    _component.set('issues', this.csvData);

  }
});

<div id="table-div">
  <input class="search" placeholder="Filter by your input">
  <button class="sort" data-sort="issue_number">Sort by Issue #</button>
  <table id='data-table' class='table table-striped table-bordered'>
    <tbody id='table-body' class="list">
      {{#each issues as |issue|}}
      <tr>
        {{#each issue as |column|}}
        <td>{{column}}</td>
        {{/each}}
      </tr>
      {{/each}}
    </tbody>
  </table>
</div>

{{yield}}