jquery - Dynamic variable names javascript MVC -


i'm running bit of javascript code in loop, creating chart (using google visualization). after code run, need access these objects somewhere else. problem can't call "chart" again, since has been over-written.

i've managed figure out hacky solution involves using mvc @ thing dynamically generate @ run-time, force variable name. works, don't think it's right way approach problem. there way me dynamically change name of variable each time it's run?

the following code run multiple times.

@{ var mychart = "cdata" + model.chartid.tostring(); } ... function () {     @mychart = new google visualization.chartwrapper({ ... });      dashboard.bind(slider, @mychart);     dashboard.draw(data);  } 

mychart changes every single time code run, giving me hacky string. putting without ' marks, becomes variable @ runtime. after run, have resize function run following:

@mychart .setoption('width', width); @mychart .setoption('height', height); @mychart .draw(); 

this super hacky. took advantage of how javascript ignores spaces, can treat @mychart object.

the result riddled syntax errors, still runs, , runs intended results. question if there "proper" solution this, instead of making separate javascript functions each individual chart need make.

thanks.

there's nothing wrong you've done, better.

first, don't have rely on space mix javascript , razor.

@(mychart).setoption('width', width); 

but that's still ugly.

approach 1

<script>      // global (usual caveats globals apply)     var charts = {};  </script>  @for( int = 0; < 10; i++ ) {     string chartid = "chart-" + i;      <script>          charts['@chartid'] = new chart();         charts['@chartid'].setoption('width', width);         charts['@chartid'].setoption('height', height);         charts['@chartid'].draw();      </script> } 

approach 2

<script>      function doresize(chart) {         chart.setoption('width', width);         chart.setoption('height', height);         chart.draw();     }  </script>  @for( int = 0; < 10; i++ ) {     <script>          (function () {              // limit scope of "chart" variable             var chart = new chart();              // perform other init              // listen resize in manner              $(window).on("resize", function() {                 doresize(chart);             });          })();      </script> } 

approach #2 preferred method manages scope , clear read.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -