gpt4 book ai didi

javascript - Ember.js:在模板中渲染谷歌图表(AKA 目标 DOM 元素仅在存在时)

转载 作者:行者123 更新时间:2023-11-29 09:52:20 25 4
gpt4 key购买 nike

我正在尝试将一个有效的 google 图表示例集成到我的 ember.js 应用程序中。问题是我不确定将 drawChart() 放在哪里函数,以便它仅在目标 DOM 元素位于页面上时运行。

我认为加载函数的正确位置是在 View 中(我看不出有任何理由将它放在模型/ Controller /路由中)。但我需要确定 drawChart()在模板完成渲染和 <div id='chart'> 之前不会被调用元素存在。

显然 View.init()太早了。 我应该在哪里调用构建函数?
它是否属于 View (也许我应该使用控件或 Handlebars 助手?)

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();
}
});

最佳答案

ui和布局相关的逻辑最好放在views中。因此,对于此任务,我建议使用 viewcomponent 。正如您已经意识到的那样,didInsertElement 事件是调用这种逻辑的合适位置,因为您需要确保 View 已插入到 DOM 和所有必需的元素中,例如 div #chart 可用。

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

我们的想法是创建一个可重复使用的 View GoogleChartView 以及一个可以包含在任何其他 View 中的关联模板 google-chart。我假设仪表板 View 最终将包括其他图表,以及将使用其模型在图表、表格等中呈现数据。此图表相关 View 已在 View 助手 {{view "googleChart"}} 的帮助下包含在内。还有一点很重要,google.load需要在head中调用。

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 类中,允许绑定(bind)属性、执行操作等。这也是一个草案例子只是为了证明这个想法。更改值操作执行旧代码,但它当然可以对 GoogleChartView 的数据属性进行修改。 GoogleChartView 的数据属性当然可以更好地利用该模型。有趣的一点是通过 this.$().find 检索 View 的 DOM,访问包含此 View 的上下文的 Controller (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 load 时, View 可能会尝试调用 drawChart 而数据尚不可用。为了克服这个问题,您可能需要在调用 drawChart 之前检查数据是否已加载。

关于javascript - Ember.js:在模板中渲染谷歌图表(AKA 目标 DOM 元素仅在存在时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com