Skip to content

Instantly share code, notes, and snippets.

@reuf
Forked from martyychang/PieChartRemoteDemo.page
Created December 20, 2015 23:09
Show Gist options
  • Save reuf/cc6ecc62d63d15203276 to your computer and use it in GitHub Desktop.
Save reuf/cc6ecc62d63d15203276 to your computer and use it in GitHub Desktop.
How to move JavaScript functions out of the global namespace when used with Visualforce chart components
<apex:page controller="PieChartRemoteController">
<script>
var noData = new Object(); // Simply a dummy placeholder for data attribute
var App = App || {}; // To hold functions
App.retrieveChartData = function(callback) {
var year = document.getElementById('theYear').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.PieChartRemoteController.getRemotePieData}',
year,
function(result, event) {
if(event.status && result && (result.constructor === Array)) {
callback(result);
myc.RemotingPieChart.show();
}
else if (event.type === 'exception') {
document.getElementById("remoteResponseErrors").innerHTML = event.message +
'<br/>' + event.where;
}
else {
document.getElementById("remoteResponseErrors").innerHTML = event.message;
}
},
{ escape: true }
);
};
App.refreshRemoteChart = function() {
var statusElement = document.getElementById('statusDisplay');
statusElement.innerHTML = "loading...";
App.retrieveChartData(function(statusElement){
return function(data){
myc.RemotingPieChart.reload(data);
statusElement.innerHTML = '';
};
}(statusElement)
);
};
</script>
<apex:pageBlock title="Charts">
<apex:pageBlockSection title="Visualforce Charting + JavaScript Remoting">
<!-- Please note that the data attribute in this example
can be thought of as simply providing a default or initial value.
Subsequent calls to RemotePieChart.reload(data) effectively
override whatever is specified in the element's data attribute.
This means that whatever you specify in the data attribute
won't matter if you simply call the refresh function. -->
<apex:chart height="350" width="450" data="noData"
name="RemotingPieChart" hidden="true">
<apex:pieSeries dataField="data" labelField="name"/>
<apex:legend position="right"/>
</apex:chart>
<div>
<select id="theYear" onChange="App.refreshRemoteChart();">
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
</select>
<span id="statusDisplay"></span>
<span id="remoteResponseErrors"></span>
</div>
</apex:pageBlockSection>
</apex:pageBlock>
<script>
// Initiate the refresh action to populate the chart
App.refreshRemoteChart();
</script>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment