All,
I am using the Flot graphing library in my rails application. I currently have a page working as expected, however all of the javascript for putting together the flot graph is inline in my “view”.html.erb file.
Is there an easy way to move the static part of the javascript to an external file, generate the dynamic data as regular in the view/controller, and pass it to the javascript file? (through “data-message”??)
The basic layout looks like this:
Controller:
@portfolios = # a bunch of portfolios
View:
<script type="text/javascript">
jQuery(document).ready(function($) {
// show & hide some stuff
var options = {
.......
};
// THIS IS THE DYNAMIC PORTION
var portfolio_collection = []
var id_lookup = []
<% @portfolios.each do |portfolio| %>
<% attribute1 = portfolio.attribute1 %>
<% attribute2 = portfolio.attribute2 %>
portfolio_collection.push([<%= attribute1 %>,<%= attribute2 %>]);
id_lookup.push([<%= portfolio.id %>]);
<% end %>
// END DYNAMIC
var plot = $.plot( // This is the plot command, puts graph in #select div
$("#select"),
[ { data: portfolio_collection, label: "Return"} ],
options
);
// A SCHWACK OF JAVASCRIPT
........
</script>
<h1>My HTML content...</h1>
<br />
<div id="select" style="width:600px;height:300px;"></div>
.... a bunch of other divs which renders javascript results from clicking on the graph ....
What I did to get around this issue, is move the flot script to the portfolios.js file. Then I bound a click event to generate the flot graph. In the anchortab I put something like this
Then in the js file I pulled the call like this
All that is left to do is build out the @portfolio_data and the @portfolio_options strings in the Portfolio Controller.