Retrieve data visualization tools from a separate function

Below is a Google dashboard featuring filtering, sorting, and paging functionality.

I need to programmatically modify the sourceData and refresh the Google visualization from outside its containing function. The challenge is accessing the visualization from a function like outsideGV.

Normally, I would call table.draw(); within renderChart_onPageLoad to redraw the visualization, but accessing it from outsideGV is proving tricky. I must ensure that user selections for paging, sorting, and filtering are maintained during refreshes.

Attempts to recall the renderChart_onPageLoad function resulted in a complete reset of user inputs, erasing all previous selections.

Your feedback would be greatly appreciated.

UPDATE: It's unlikely that there will be a single variable (data, for example) on a page. I have a dedicated data variable for each chart on the page.

Multiple Google tables are drawn on the page by the drawDashboard_ function. Is it feasible to compile references to these tables in a global array?

const globalReferences = [];

I aim to populate this array as each drawDashboard_ function is executed. Can these references be collected after all variables are created?

globalReferences.push({
  "chartID": suffix, //unique identifier for each function pass
  "data": data,
  "dashboard": dashboard,
  "categoryPicker": categoryPicker,
  "proxyTable": proxyTable,
  "table": table
});

Is it possible to then reference this array to access a specific chart?

globalReferences[0].table; 
//retrieve the reference, make changes, and redraw.

google.charts.load('current', {
  'packages': ['corechart', 'table', 'gauge', 'controls', 'charteditor']
});

var listenerPage = {};
var listenerSort = {};

var sourceData = [
  ['Name', 'RoolNumber', 'Gender', 'Age', 'DonutsEaten'],
  ['Michael', 1, 'Male', 12, 5],
  ['Elisa', 2, 'Female', 20, 7],
  ['Robert', 3, 'Male', 7, 3],
  ['John', 4, 'Male', 54, 2],
  ['Jessica', 5, 'Female', 22, 6],
  ['Aaron', 6, 'Male', 3, 1],
  ['Margareth', 7, 'Female', 42, 8],
  ['Miranda', 8, 'Female', 33, 6]
]

$(document).ready(function() {
  renderChart_onPageLoad();
});

function referenceGV() {

  //ON BUTTON CLICK 
  //1 UPDATD sourceData - Make a change programatically
  //1 REFRESH GV
  //    must retaining all selected user filtering, sorting, paging

}

function renderChart_onPageLoad() {
  google.charts.setOnLoadCallback(function() {
    drawDashboard_A("A");
  });
}

function drawDashboard_A(suffix) {

  var data = google.visualization.arrayToDataTable(sourceData);

  var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_' + suffix));

  var categoryPicker = new google.visualization.ControlWrapper({
    controlType: 'CategoryFilter',
    containerId: 'categoryPicker_' + suffix,
    options: {
      filterColumnLabel: 'Gender',
      ui: {
        labelStacking: 'vertical',
        allowTyping: false,
        allowMultiple: false
      }
    }
  });

  var proxyTable = new google.visualization.ChartWrapper({
    chartType: 'Table',
    containerId: 'proxyTable_' + suffix,
    options: {
      width: '500px'
    }
  });

... (Content truncated for brevity) ...

</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dashboardA">
  <div id="categoryPicker_A"></div><br />
  <div id="proxyTable_A" style="display:none;"></div>
  <div id="table_A"></div><br /><br />
</div>

<button onclick="referenceGV()">
referenceGV
</button>

Answer №1

Make sure to declare your variables in the global space, just like your sourceData...

Also, remember to remove the var statement from the original declarations.

But be cautious not to attempt to access the variables before they are created...

google.charts.load('current', {
  'packages': ['corechart', 'table', 'gauge', 'controls', 'charteditor']
});

var listenerPage = {};
var listenerSort = {};

var sourceData = [
  ['Name', 'RoolNumber', 'Gender', 'Age', 'DonutsEaten'],
  ['Michael', 1, 'Male', 12, 5],
  ['Elisa', 2, 'Female', 20, 7],
  ['Robert', 3, 'Male', 7, 3],
  ['John', 4, 'Male', 54, 2],
  ['Jessica', 5, 'Female', 22, 6],
  ['Aaron', 6, 'Male', 3, 1],
  ['Margareth', 7, 'Female', 42, 8],
  ['Miranda', 8, 'Female', 33, 6]
]

// Global variable declarations
var data;
var dashboard;
var categoryPicker;
var proxyTable;
var table;


$(document).ready(function() {
  renderChart_onPageLoad();
});

function referenceGV() {

  //ON BUTTON CLICK 
  //1 UPDATD sourceData - Make a change programatically
  //1 REFRESH GV
  //    must retaining all selected user filtering, sorting, paging

}

function renderChart_onPageLoad() {
  google.charts.setOnLoadCallback(function() {
    drawDashboard_A("A");
  });
}

function drawDashboard_A(suffix) {

  // Remove var statement from here
  data = google.visualization.arrayToDataTable(sourceData);

  dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_' + suffix));

  categoryPicker = new google.visualization.ControlWrapper({
    controlType: 'CategoryFilter',
    containerId: 'categoryPicker_' + suffix,
    options: {
      filterColumnLabel: 'Gender',
      ui: {
        labelStacking: 'vertical',
        allowTyping: false,
        allowMultiple: false
      }
    }
  });

  proxyTable = new google.visualization.ChartWrapper({
    chartType: 'Table',
    containerId: 'proxyTable_' + suffix,
    options: {
      width: '500px'
    }
  });

  table = new google.visualization.ChartWrapper({
    chartType: 'Table',
    containerId: 'table_' + suffix,
    options: {
      sort: 'event', // <-- set sort to 'event' for table totaling
      width: '500px',
      allowHtml: true,
      page: 'enable',
      pageSize: '3',
    }
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining Import and Require in a Node JS File

Having some trouble with the normalize-url package. It needs to be imported instead of required since it's not supported in ES module. I tried to work around this by adding some code I found online, but it doesn't seem to be fixing the issue for ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

How do I modify the date format displayed in the Bootstrap 4 datetimepicker when sending the value?

I have a datetimepicker() set with ID start_date that matches an input name. In the props, the format is specified as YYYY-MM-DD. I want to use this format for my API, but I want the user to see the date displayed in the format DD-MM-YYYY. $('#start_ ...

Utilizing Angular.js to nest directives seamlessly without cluttering the markup

Expressing my query might pose some difficulty, but I appreciate your patience. I comprehend that in the realm of Angular.js, directives play a crucial role in driving dynamic markup. What was once achieved through jQuery can now be accomplished using dir ...

Convert my information to an XML document

Successfully, I have loaded the content of an XML file into my PHP document using the following method: $(document).ready(function () { $.ajax({ type: "GET", url: "abstimmer.xml", dataType: "xml", success: function ...

How can you turn off CSS3 animations for browsers that don't support them

Upon page load, a fade-in animation is applied to the main container. Although it functions properly in most browsers, it seems to have an issue in IE(9). Is there a method to identify if the user's browser does not support CSS3 animations and disabl ...

Javascript initial keypress delay for movement in 3D space

I am aiming for a seamless movement experience when pressing a key - with the object initiating its movement upon the first press and then continuously moving while the button is held down. //setting movement speeds var xSpeed = 0.5; var zSpeed = 0.5; do ...

The json_encode() function yields an empty result

I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...

Using Vue.js, separate the values that are separated by commas

I am looking to extract values from a string and store them in an array for use in displaying values in a dropdown format within Vuejs String str = "abc,123,676,uuu". Once I have iterated through the values <li v-for = "value i ...

Google Maps displays grayscale overlays on the latest version update

Hello, I am facing a challenging issue with the Google Maps API. I have come across some similar threads discussing this problem, but unfortunately, they did not provide a solution that suits my specific case. Currently, I am working on an angular.js 1. ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

The issue persists as AJAX data and text box data are not being saved simultaneously

I need assistance with an Ajax setup. I am trying to pass the screenwidth information along with a user input value from a text box to a PHP page. However, I am encountering issues as the only value being passed is from the textbox and the other one is sho ...

Apply bold formatting to the HTML text only, leaving the EJS variable untouched beside it

https://i.sstatic.net/X36eG.png Is there a way to format the text for "Guest signed up" and "Guests attended" in bold while keeping the values normal? Here is my current code: <li class="list-group-item">Guests signed up: <%= guestSignu ...

What method is used to initialize the variables in this JavaScript snippet, and what other inquiries are posed?

As a backend developer, I'm looking to understand this JavaScript snippet. While I grasp some parts and have added comments where I am clear, there are still sections that leave me with bold questions. function transformData (output) { // QUESTIO ...

Modifying the order of Vuetify CSS in webpack build process

While developing a web app using Vue (3.1.3) and Vuetify (1.3.8), everything appeared to be working fine initially. However, when I proceeded with the production build, I noticed that Vue was somehow changing the order of CSS. The issue specifically revol ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false: function submitValidate() { var xmlhttp; xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari try { xmlhttp ...

How can we arrange a two-dimensional array in descending order of string length using the first string in the sub-array as the basis for

If I have an array with elements like these: var array = [["This should be last", 1], ["This should be first I think", 1], ["This is the middle one", 1]]; The second value in each sub-array, which is always 1 in this case, doesn ...