javascript - d3 not reacting to node hash change in other require file -


i have javascript project using requirejs. have d3-and-svg.js file, , here preview of it:

var nodes = {     "at":   {id: "at", importance: 1, type: 'exercise', displayname: 'pigeonhole principal'},     "b":    {id: "b", importance: 8, type: "theorem", displayname: 'pigeonhole theorem'}, },     links = []  var width = $(window).width(),     height = $(window).height()  var force = d3.layout.force()     .nodes(nodes) // here nodes go in     .links(links)     .size([width, height])     .charge(-400)     .linkstrength(0.2)     .gravity(0.05)     .on('tick', updatesvgnodeandlinkpositions) 

i have modified d3 library accept hashes, so:

force.nodes = function(x) {   if (!arguments.length) return nodes;   // setup helper function   function hash_to_array(hash) {     var array = [];     for( key in hash ){ if( hash.hasownproperty(key) ){       array.push( hash[key] );     }}     return array;   };   nodes = hash_to_array(x); // means .nodes() takes hash input , uses values   // nodes = x; // used   return force; }; 

and in main.js file, kickoff d3 force animation, so:

d3andsvg.processnewgraph(); 

and works! works! funny thing is, if replace nodes empty hash in d3-and-svg.js file, , populate via main.js file instead, so:

d3andsvg.nodes = {     "at":   {id: "at", importance: 1, type: 'exercise', displayname: 'pigeonhole principal'},     "b":    {id: "b", importance: 8, type: "theorem", displayname: 'pigeonhole theorem'}, } d3andsvg.processnewgraph(); 

then not work. why not? thing can think of values of hash references, , d3-and-svg.js can't access them when in other file. not sure this, nor can think of solution.

with code you've shown, cannot work. define nodes:

var nodes = ... 

which presumably local module's factory (the function pass define). use as:

var force = d3.layout.force()     .nodes(nodes) // here nodes go in     ... 

this nodes, again local module's factory. perhaps forgot export nodes, you'd exports.nodes = nodes. however, alone won't it. see, when outside module:

d3andsvg.nodes = // whatever 

you changing exported value of nodes (i.e. set exports.nodes = ...) refer different object. however, local value of nodes, using force remains unchanged. situation same in interactive node.js session:

> var = { foo: 'a'} > { foo: 'a' } > var b = > b { foo: 'a' } > b = { foo: 'b' } // assign new object `b`. { foo: 'b' } > b { foo: 'b' } > { foo: 'a' } 

the value of a did not change when assigned new object b.

what can have code honor changes d3andsvg.nodes have code uses nodes use exports.nodes instead:

var force = d3.layout.force()     .nodes(exports.nodes) // here nodes go in     ... 

Comments