Chuck Carlson
Chuck Carlson

Reputation: 987

How to call javascript function in module

I get an Uncaught ReferenceError for generateChart.

I've defined generateChart in Chart.js which is referenced in require.config.js.

I'm new to javascript and require so this is a newbee question.

Here is my code:

main html file:

<!DOCTYPE html>
<html>
<meta charset="utf-8">

<body>

<p id="example">

<script src="js/require.config.js"></script>
<script data-main="js/config.js" src="js/lib/require.js"></script>


</body>

require.config.js

var require = {
    paths: {
        'd3': 'lib/d3',
        'Chart' : 'Chart'
    }
};

config.js which contains the main entry point and the unreferenced call to generateChart

define([
    'd3',
    'Chart'
], function (d3, Chart) {
    'use strict';


	d3.csv("sp500.csv", function(data) {

  	d3.select("#example")
      	.datum(data)
    	.call(generateChart());
	});

});

And Chart.js where I define generateChart

define([
    'd3'
], function (d3) {
    'use strict';

    generateChart = function() {
    };

 });

Upvotes: 1

Views: 727

Answers (1)

Borys Serebrov
Borys Serebrov

Reputation: 16172

I am not require.js user, but it looks that dependencies are passed into the function you specify inside the define. This way the second parameter in the code below should represent Chart module and you need to use it to call the generateChart:

define([
    'd3',
    'Chart'
], function (d3, Chart) {    /// Second parameter is 'Chart'
    'use strict';


    d3.csv("sp500.csv", function(data) {

    d3.select("#example")
        .datum(data)
        .call(Chart.generateChart());   /// use it here to call generateChart()
    });

});

Second issue is that Chart.js should return an object and not just define a function:

define([
    'd3'
], function (d3) {
    'use strict';

    return {
        generateChart: function() {
           alert('here');
        }
    }

 });

Upvotes: 1

Related Questions