Categories
Java Script Tutorials

Registering JavaScript Events can be Tricky

When registering JavaScript Events we need to provide the handler. That handler is called when ever a specified event is clicked.

function clickHandler() {
  alert('Window is clicked')
}

window.addEventListener('click', clickHandler())

The problem with above code is that, we will see the alert as soon as windows loads. The expected result is show alert whenever we click on that.

Click for the solution or continue reading for and how I diagnosed it.

Diagnosing JavaScript Events

While working with blueprint-3d (application that allows users to design an interior space such as a home or apartment) that uses three.js (JavaScript 3D libray), I used the Event Dispatcher. Now the blueprint-3d also used but it would trigger once. When I used it would trigger more than one time. After spending some hours in despair, I tried to mimic the way it was done by vue-blueprint 3d.

They used it like this

this.scene.addEventListener(EVENT_ITEM_LOADED, this.itemloadedevent);
itemloadedevent(){
}

I was using it like this

this.scene.addEventListener(EVENT_ITEM_LOADED, () => {
 })

What I am doing, I calling a function at the time of event registration. I should just give reference of the function but not call it. Writing it the way it was written by blueprint-3d, it worked!.

It is weird that I tried using arrow function which worked perfectly in first example but not with blueprint-3d

Solution

Let’s fix our original example. All we have to do is not execute the function but just give the reference of the hander.

function clickHandler() {
  alert('Window is clicked')
}

window.addEventListener('click', clickHandler)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.