EventBus element click listener

Hey there,
I want to access the ID and type of each element that user clicks on. I can access it using eventBus, but the problem of this method is that it’s only possible to log this data inside the eventBus. Neither it is possible to pass this data out, nor it is to call another function inside it. I’m using bpmn.js in an Angular project and here’s my code:

          let element : bpmnElement;
          this.eventBus = this.bpmnJS.get("eventBus");
          this.eventBus.on("element.click", function(event) {
            element = {
              id: event.element.id,
              type: event.element.type
            }
          });
          console.log(element)

here, the console.log prints “undefined”, but if I put it inside the eventBus function, it works fine.

console.log in your code snippet is executed as soon as the callback is registered. Indeed, to log the element value at time when the element is clicked, you need to put console.log inside. Read more on callbacks in JavaScript at Callback function - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

What do you want to achieve in your project?

1 Like

thanks for the quick response.
yes, I know that I should put console.log inside. The problem is that I want to pass the element data to ngrx (angular’s state managar) and this seems not to be possible. Logging the data or alerting it is fine, but it’s not possible to call a service or another function in my component inside the eventBus. In other words, it’s not possible to have this data outside of EventBus.

Please share a running / prototypical example that clearly shows what you’re trying to achieve, what is working and what is not.

Use our existing starter projects to quickly hack it or share your existing, partial solution on GitHub or via a CodeSandbox. Provide the necessary pointers that allow us to quickly understand where you got stuck.

This way we may be able to help you in a constructive manner.

Thanks :heart:

Just guessing here…

If the ngrx is assigned to the context, you could probably just pass an arrow function to the Event Bus like so:

          let element : bpmnElement;
          this.eventBus = this.bpmnJS.get("eventBus");
          this.eventBus.on("element.click", (event) => {
            element = {
              id: event.element.id,
              type: event.element.type
            }
            this.ngrxStore.dispatch(element);
          });
1 Like

Great! This works perfectly.
Thank you @barmac

1 Like