Unable to access a class method inside an event handler TypeError: Cannot read property "x" of null

Continuing the discussion from Some questions about some specific needs and whether bpmn-js can ensure them:

I tried following answer that Niklas_Kiefer kindly provided in the linked topic above(for global context).

You can have a look into this thread answer. It shows how to disable the direct editing for an element via double clicking (returning false). With this event handler, it would also be possible to add your custom logic, e.g. opening a modal.

So I implemented this event handler that is supposed to open an angular dialog(can be found in the codesandbox linked below in the ngOnInit lifecycle hook.

    let eventBus = this.bpmnJS.get("eventBus");

    eventBus.on("element.dblclick", 2000, function (context) {
      console.log("selected");
      this.openDialog();
    });

But whenever the event is triggered I get the error :

TypeError: Cannot read property ‘openDialog’ of null

So, I’m guessing it’s referring at the keyword “this” being interpreted as null.

I reproduced my issue in this codesandbox.
I also added a button that opens the dialog, and double clicking on an element throws the said error.

image

The answer might seem clear for some, but I’m new to javascript and web development in general this fixed the issue for me(probably an issue related to scopes).
For anyone else having the same issue try this or check the sandbox above:

    let x=this;
    eventBus.on("element.dblclick", 2000, function (context) {
      console.log("selected");
      x.openDialog();
    });
1 Like

In JavaScript, this changes depending on where you’re invoking it. If you want to make a specific instance of this persist, you need to do as you did, put it in a variable to be reused later.
You would usually call it something like self.

1 Like