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?
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.
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.
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 ...
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.
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) { /* .... */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With