Ember.js:在模板中呈现谷歌图表(仅在存在时为AKA目标DOM元素)

时间:2013-11-25 16:39:25

标签: javascript model-view-controller ember.js google-visualization

我正在尝试将一个正在运行的Google图表示例集成到我的ember.js应用中。问题是,我不确定将drawChart()函数放在何处,以便仅在页面上的目标DOM元素运行时才运行。

我认为加载功能的正确位置在视图中(我没有看到任何理由将其放入模型/控制器/路由中)。但是我需要确保在模板完成渲染并且drawChart()元素存在之后才调用<div id='chart'>

显然View.init()太早了。 我应该在哪里调用构建函数?
它甚至属于一个视图(也许我应该使用控件或把手助手?)

App.DashboardView = Ember.View.extend({
  name: "",
  init: function(){
    // this breaks the app...
    //google.load("visualization", "1", {packages:["corechart"]});
    //google.setOnLoadCallback(drawBarGraph);
    this.set('name', 'ted');
    return this._super();
  }
});

1 个答案:

答案 0 :(得分:5)

最好在views中放置与ui和布局相关的逻辑。因此,对于此任务,我建议使用viewcomponent。正如您已经意识到didInsertElement事件是调用此类逻辑的适当位置,因为您需要确保已将视图插入到DOM中,并且所有必需元素(如div#chart)都可用

我提供的解决方案有点粗糙但是给出了一个起点。

我们的想法是创建一个可重复使用的视图GoogleChartView,其中包含可以包含在任何其他视图中的关联模板google-chart。我假设仪表板视图最终将包括其他图表,这些图表将使用其模型在图表,表格等中显示数据。 此视图相关视图已包含在视图助手{{view "googleChart"}}的帮助下。另一个重点是google.load需要被调用。

http://jsbin.com/oCIcexOB/1/edit

<强> JS

App = Ember.Application.create();


/******** VIEWS ********/
App.DashboardView = Ember.View.extend({
  name: "",
  init: function(){
    //google.load("visualization", "1", {packages:["corechart"]});
    //google.setOnLoadCallback(drawBarGraph);
    this.set('name', 'ted');
    return this._super();
  }
});

App.GoogleChartView = Ember.View.extend({
  templateName:"google-chart",
  drawChart:function(){

    drawChart();

  }.on("didInsertElement")
});

/******** ROUTES ********/
App.Router.map(function() {
  this.resource('items');
  this.resource('dashboard');
});
App.IndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('items');
  }
});
App.ItemsRoute = Ember.Route.extend({
  model: function() {
    var a = Em.A();
    a.pushObject( App.Item.create({title: 'A', cost: '100', options: buildMockOptions('A')}));
    a.pushObject( App.Item.create({title: 'B', cost: '200', options: buildMockOptions('B')}));
    a.pushObject( App.Item.create({title: 'C', cost: '300', options: buildMockOptions('C')}));
    return a;
  }
});

buildMockOptions = function(someVar){
  var arr = [];
  for(var i = 0;i<3;i++){
    var opt = App.Option.create({someOption: 'Option for ' + someVar + ': ' + i});
    opt.cost = 5;
    arr.pushObject(opt);
  }
  return arr;
};

/******** MODELS ********/
App.Item = Ember.Object.extend({
  title: '',
  cost: '',
  quantity: '',
  options: null,

  totalOptionsCost: function(){
    var j = this.get('options').reduce(
      function(prevValue, currentValue, index, array){ 
        return prevValue + parseInt(currentValue.get('cost'), 10); }, 0);
    return j;
  }.property('options.@each.cost')
});

App.Option = Ember.Object.extend({
  someOption: '',
  cost: ''
});


/******** CONTROLLERS ********/
App.ItemsController = Ember.ArrayController.extend({
  len: function(){
    return this.get('length');
  }.property('length'),

  totalCost: function() {
    return this.reduce( function(prevCost, cost){
      return parseInt(cost.get('cost'),10) + prevCost;
    }, 0);
  }.property('@each.cost'),

  totalOptions: function(){
    var opts = this.mapBy('options');
    return [].concat.apply([], opts).length;
  }.property(),

  totalOptionCost: function(){
    var sum = this.reduce(function(prev, curr){ 
      return prev + curr.get('totalOptionsCost');},0);
    return sum;
  }.property('@each.totalOptionsCost')
});

App.DashboardController = Em.Controller.extend({
  needs: ['items'],
  itemsLength: Ember.computed.alias('controllers.items.len'),
  itemsTotalCost: Ember.computed.alias('controllers.items.totalCost'),
  optionsTotal: Ember.computed.alias('controllers.items.totalOptions'),
  optionsCost: Ember.computed.alias('controllers.items.totalOptionCost')
});

// GOOGLE CHART FUNCTION
function drawChart() {

  // Create and populate the data table.
  var options = {
      title:"Yearly Coffee Consumption",
      width:600, 
      height:400,
      animation: {duration: 1000, easing: 'out'},
      vAxis: {title: "Cups", minValue:0, maxValue:500},
      hAxis: {title: "Year"}
  };

  var data = new google.visualization.DataTable();    
  data.addColumn('string', 'N');
  data.addColumn('number', 'Value');
  data.addRow(['2003', 0]);
  data.addRow(['2004', 0]);
  data.addRow(['2005', 0]);

  // Create and draw the visualization.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
  chart.draw(data, options);
  data.setValue(0, 1, 400);
  data.setValue(1, 1, 300);
  data.setValue(2, 1, 400);
  chart.draw(data, options);

    var button = document.getElementById('b1');
    button.onclick = function() {

      if (data.getNumberOfRows() > 5) {
        data.removeRow(Math.floor(Math.random() * data.getNumberOfRows()));
      }
      // Generating a random x, y pair and inserting it so rows are sorted.
      var x = Math.floor(Math.random() * 10000);
      var y = Math.floor(Math.random() * 1000);
      var row = 0;
      while (row < data.getNumberOfRows() && parseInt(data.getValue(row, 0),10) < x) {
        row++;
      }
      data.insertRows(row, [[x.toString(), y]]);
      chart.draw(data, options);
    };
}

function drawChart() {

  // Create and populate the data table.
  var options = {
      title:"Yearly Coffee Consumption",
      width:600, 
      height:400,
      animation: {duration: 1000, easing: 'out'},
      vAxis: {title: "Cups", minValue:0, maxValue:500},
      hAxis: {title: "Year"}
  };

  var data = new google.visualization.DataTable();    
  data.addColumn('string', 'N');
  data.addColumn('number', 'Value');
  data.addRow(['2003', 0]);
  data.addRow(['2004', 0]);
  data.addRow(['2005', 0]);

  // Create and draw the visualization.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
  chart.draw(data, options);
  data.setValue(0, 1, 400);
  data.setValue(1, 1, 300);
  data.setValue(2, 1, 400);
  chart.draw(data, options);

    var button = document.getElementById('b1');
    button.onclick = function() {

      if (data.getNumberOfRows() > 5) {
        data.removeRow(Math.floor(Math.random() * data.getNumberOfRows()));
      }
      // Generating a random x, y pair and inserting it so rows are sorted.
      var x = Math.floor(Math.random() * 10000);
      var y = Math.floor(Math.random() * 1000);
      var row = 0;
      while (row < data.getNumberOfRows() && parseInt(data.getValue(row, 0),10) < x) {
        row++;
      }
      data.insertRows(row, [[x.toString(), y]]);
      chart.draw(data, options);
    };

}

<强> HTML

<!DOCTYPE html>
<html>
<head>
  <meta name="description" content="Ember.js example: Trying to display a google chart in a template." />
<meta charset=utf-8 />
<title>JS Bin</title>
  <script src="http://www.google.com/jsapi?ext.js"></script>
  <script src="http://code.jquery.com/jquery-2.0.2.js"></script>
  <script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
  <script src="http://builds.emberjs.com/ember-latest.js"></script>
  <script src="http://www.google.com/jsapi?ext.js"></script>
  <script>google.load("visualization", "1", {packages:["corechart"]});</script>
</head>
<body>

  <script type="text/x-handlebars" data-template-name="application">
  <p><strong>Ember.js example:</strong><br> Trying to display a google chart in a template.</p>
  <p>This jsbin represents a dashboard that analyzes a hierarchy of items and child 'options' and visualizes that info in a 'dashboard' section'. Currently, I am trying to integrate a google chart into the dashboard right above the 'Change Value' button.</p>

  <p>Google chart example: <a href='http://jsfiddle.net/doub1ejack/h7mSQ/96/'>http://jsfiddle.net/doub1ejack/h7mSQ/96/</a><br>
  Stackoverflow post: <a href='http://stackoverflow.com/questions/20198317/ember-js-rendering-google-chart-in-template-aka-target-dom-element-only-when-p'>http://stackoverflow.com/questions/20198317/...</a></p>

    {{render dashboard}}
    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="items">
    <h2>Items:</h2>
    <dl>
      {{#each}}
        <dt>Item: {{title}}</dt>
        <dd>Cost: {{cost}}</dd>

        <dd class='options'>{{render 'options' options}}</dd>
      {{/each}}
    </dl>
  </script>

   <script type="text/x-handlebars" data-template-name="options">
    {{log controller}}
    <dl>
      {{#each option in controller }}
        <dt>{{option.someOption}}</dt>
        <dd>Option cost: {{option.cost}}</dd>
      {{/each}}
    </dl>
  </script>


  <script type="text/x-handlebars" data-template-name="dashboard">
    <h2>Dashboard:</h2>

    {{view "googleChart"}}
    <div id="chart"></div>

    {{! ITEM/OPTION ANALYSIS }}
    {{#if controllers.items}}
    <h3>Item Overview:</h3>
    Total number of items (expect 3): {{itemsLength}}<br>
    Total cost of items (expect 600): {{itemsTotalCost}}
    <h3>Option Overview:</h3>
    Total number of options (expect 30): {{optionsTotal}}<br>
    Total cost of options (expect 45): {{optionsCost}}
    {{/if}}
  </script>

  <script type="text/x-handlebars" data-template-name="google-chart">
    <div id="chart"></div>
<form><input id="b1" type="button" value="Change Value"/></form>
  </script>

</body>
</html>

修改

这是另一个示例,其中包含与绘制图表相关的属性和数据的代码在GoogleChartView类中容纳,允许绑定属性,执行操作等。这也是一个草案示例证明这个想法。更改值操作执行旧代码,但它肯定可以修改GoogleChartView的data属性。 GoogleChartView的数据属性当然可以更好地利用该模型。有趣的是通过this.$().find检索视图的DOM,访问包含此视图的上下文的控制器(DashboardController),因为此时可以检索,解析和绘制任何数据。

http://jsbin.com/UHajoX/1/edit

App.GoogleChartView = Ember.View.extend({
  templateName:"google-chart",
  chart:null,
  options:{
      title:"Yearly Coffee Consumption",
      width:600, 
      height:400,
      animation: {duration: 1000, easing: 'out'},
      vAxis: {title: "Cups", minValue:0, maxValue:500},
      hAxis: {title: "Year"}
  },
  data:function(){

    var items = this.get("controller").get("items");

    var chartData = new google.visualization.DataTable();
    chartData.addColumn('string', 'N');
    chartData.addColumn('number', 'Value');
    chartData.addRow(['2003', 0]);
    chartData.addRow(['2004', 0]);
    chartData.addRow(['2005', 0]);

    items.forEach(function(item,index){
      chartData.setValue(index,1,parseInt(item.get("cost"),10));

    });
   /*chartData.setValue(0, 1, 400);
    chartData.setValue(1, 1, 300);
    chartData.setValue(2, 1, 400);*/



    return chartData;
  }.property(),
  drawChart:function(){

    this.drawChart2();

  }.on("didInsertElement"),
  drawChart2:function(){

  var data = this.get("data");

  // Create and draw the visualization.
  this.set("chart", new google.visualization.ColumnChart(this.$().find('#chart').get(0)));
  this.get("chart").draw(data, this.get("options"));


  },
    actions:{
      changeValue:function(){
        var data = this.get("data");
      if (data.getNumberOfRows() > 5) {
        data.removeRow(Math.floor(Math.random() * data.getNumberOfRows()));
      }
      // Generating a random x, y pair and inserting it so rows are sorted.
      var x = Math.floor(Math.random() * 10000);
      var y = Math.floor(Math.random() * 1000);
      var row = 0;
      while (row < data.getNumberOfRows() && parseInt(data.getValue(row, 0),10) < x) {
        row++;
      }
      data.insertRows(row, [[x.toString(), y]]);
      this.set("data",data);

      this.get("chart").draw(data, this.get("options"));   
      }
    }
});

<强>警告: 我想将来数据可能来自ember应用程序本身,但现在调用google加载时,视图可能会尝试调用drawChart并且数据尚未可用。要解决此问题,您可能需要在调用drawChart之前检查数据是否已加载。