Question

I'm writing a gem which helps to create charts easily. Gem is some "superstructure" of d3.js library...

So, I'm trying to write some helper chart_for, which must create chart on html page.

example of helper:


    def chart_for(text)
      bar_chart = %q[
        $( document ).ready(function() {
          var data = [4, 8, 16, 20, 12, 48];
          var x    = d3.scale.linear().domain( [0, d3.max(data)] ).range( [0, 420] );
          d3.select( ".chart" ).selectAll( "div" ).data( data ).enter().append( "div" ).style( "width", function( d ){ return x( d ) + "px"; } ).text( function( d ){ return d; } );
        });
      ]
      javascript_tag( bar_chart )
    end

But, unfortunately I have some problem with JS loading.

It's source of my page:

chart_for helper on html page

And last few lines of page:

enter image description here

And error:

error

As I understood, browser try run JS from my helper before the d3.js is loaded on page. How can I fix it?

Maybe my helper must write JS-code not into html.erb file, and into js file?

Maybe I need to redefine javascript_tag to write JS-code from helper into the end of html page?

Please, push me in the right direction :)

Was it helpful?

Solution 2

This helper attachs JS code to the middle of page, when jquery is not defined - js defined on the bottom of page and at this moment browser don't know about it. That's why current error appears.

What to do:

  1. move JS code from helper to JS file and attach it to the page bottom after jquery.js and d3.js files
  2. change helper content to tag with some #id
  3. associate your JS code with with #id element

OTHER TIPS

Can you try

jQuery(document).ready(function() {

Instead of

$(document).ready(function() {

I used to have conflicts with $ with some library I used. This did a quick but unconventional trick for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top