0

In the below code, the function dragstarted() is D3 JS function that gets called everytime a graph node is clicked (which gets called fine). However, it is not possible to change 'clicked' or call 'onRelatedEntityClick' from the callback function for some reason. I wonder what I am doing wrong? 'onRelatedEntityClick' simply doesn't get called as confirmed by console messages not getting printed.

export default class entityGraphicalDisplay extends LightningElement 
{
    @api children;
    @api parents;
    @api entity;

    clicked='none';

    svgHeight = 400;
    svgWidth = 800;

    d3Initialized = false;

    onRelatedEntityClick(d)
    {
        console.log('related entity click called for: ', d);
        
    }
    
    renderedCallback() {
        console.log('Rendered callback called');
        if (this.d3Initialized) {
            return;
        }
        this.d3Initialized = true;

        Promise.all([
            loadScript(this, D3 + '/d3.v5.min.js'),
            loadStyle(this, D3 + '/style.css')
        ])
            .then(() => {
                this.initializeD3();
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error loading D3',
                        message: error.message,
                        variant: 'error'
                    })
                );
            });
    }

    initializeD3() {
      
        

        function dragstarted(d) 
        {
            console.log('Function called'); //Function gets called everytime a node is clicked.
console.log(this.clicked); //Result = undefined on console (why?)
            this.clicked = d.name; // Doesnt update top-level variable despite the function being called.
            console.log('Updated clicked: ', this.clicked);
            this.onRelatedEntityClick(d); //Top level function doesnt execute similar to how top level variable doesnt get updated.
            

            if (!d3.event.active) simulation.alphaTarget(0.1).restart();
            d.fx = d.x;
            d.fy = d.y;
        }
        
       function start(graph) {
        
           ....
          
        }
        
        start(graph);
    }
}```

1 Answer 1

4
function dragstarted(d) 

Creates a new this context. You need to either use an arrow function, or bind to a function on the class.

dragstarted(d) => {

Or

let dragstarted = function(d) { ... }
dragstarted = dragstarted.bind(this);
1
  • Using the second one solved by problem. Thanks for the quick response, really appreciate it. Upvoted and marked as correct. Commented Jun 4, 2022 at 21:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .