Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to integrate d3 with require.js

Tags:

I'm having problems trying to integrate d3 into a require/backbone application. My main.js contains something like:

require.config({   paths: {     d3: 'libs/d3/d3.v2.min'     backbone: ...     ...   } }); 

And my backbone view something like (in coffeescript)

define ['backbone','d3',...], (Backbone,d3,...) ->   MyView = Backbone.View.extend     initialize: () ->       d3.somefunction 

Console log says d3 is null. Is there a simple way to integrate d3 into this type of application?

like image 292
Serge Anido Avatar asked Oct 31 '12 12:10

Serge Anido


People also ask

How Include RequireJS?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.

Where do I put D3 js code?

D3. js is a JavaScript code, so we should write all our D3 code within “script” tag. We may need to manipulate the existing DOM elements, so it is advisable to write the D3 code just before the end of the “body” tag.

Do you want to use RequireJS?

RequireJS is a basic loader, which is used to loads the JavaScript files, it is a framework to manage dependencies between JavaScript files, and in modular programming, all the functionality divides in different modules, so RequireJs is a best tool to assemble different JavaScript files from different modules by which ...


2 Answers

d3 does not call define() to declare a module, so the local d3 reference to the backbone view will not be what you want. Either use the global variable made by d3:

define(['backbone', 'd3'], function (backbone, ignore) {     //Use global d3     console.log(d3); }); 

Or use the shim config to declare an exports value for d3:

requirejs.config({     shim: {         d3: {             exports: 'd3'         }     } }); 

That will tell requirejs to use the global d3 as the module value for d3.

like image 117
jrburke Avatar answered Sep 25 '22 22:09

jrburke


Since d3.v3 now registers itself as an AMD module if a compatible library is present, you'll need to use this workaround (from http://pastebin.com/d5ZDXzL2):

requirejs.config({     paths: {         d3: "scripts/d3.v3",         nvd3: "scripts/nv.d3"     },     shim: {         nvd3: {           exports: 'nv',           deps: ['d3.global']         }     } }); // workaround for nvd3 using global d3 define("d3.global", ["d3"], function(_) {   d3 = _; });  define('myModule', ['nvd3'], function(nc) { /* .... */ }); 
like image 40
webXL Avatar answered Sep 21 '22 22:09

webXL