1

I have a function that builds my d3 display, within it is a function called update() which actually deals with the nodes.

The function can be seen here

As you can see, the svg tree is created and then the update() function is run, displaying the tree nodes.

When a tree node with a certain data attribute is clicked, an html form is appended to the screen which allows a user to add data relating to that node. The user enters the data, clicks 'save' which has a jQuery based event handler attached which updates the data source.

I need to then trigger the tree to update with the node showing the new data.

I'm unsure how to trigger this update() function from an external function. I don't want to have to rebuild the entire tree every time, just redraw the nodes to show the new data.

Where is the gap in my understanding of how to do this?

VK Da NINJA
  • 512
  • 7
  • 19
deadlysyntax
  • 144
  • 9

1 Answers1

2

This seems to be more of a JavaScript scope issue. Is tree_data already exposed to other functions (e.g. in the jQuery event handler, can you console.log(tree_data)? If so, then we just need an external reference to update.

A quick way is to assign it to the global window scope:

window.update = function(source) { ...

Of course this isn's not optimal, but it does help us narrow down your issue.

If that works, then we just need to declare a variable outside the scope of your build: function(tree_data) and then inside, on line 65, assign it to update:

var externalReferenceToUpdate;

[...]

build: function(tree_data) {
[...]
   var update = function(source) {
   [...]
   };
   externalReferenceToUpdate = update;

   update(root);  // moved this due to function expression vs. declaration

   [...]
}

As you noticed, we had to move update(root). This is because we've "made" the function using a different method. There's a whole other Stack Overflow discussion on the ways to declare functions and their scope issues. Essentially with the second way (var name = function()), the function is not "hoisted" to the top of its scope, so we had to call update after we assigned it to a variable.

Hope this helps!

PS In that other discussion, skim over the first answer and actually focus on the second answer by Eugene.

Community
  • 1
  • 1
al lin
  • 206
  • 1
  • 4
  • Perfect. I simply needed to refactor the update function to a new scope which means setting all d3 "build" variables into an object that could be referenced within the update function and moving the update function out of the build function. Trust hindsight to make you feel silly. – deadlysyntax Jul 24 '15 at 00:45