Src
Src

Reputation: 5482

Javascript automatic function execution

If i'm writing event in this way, action executes when it should:

 document.getElementById('myElem').onmousedown = (e) => {
     console.log('fired!')
    }

But if i'm writing same stuff in other way, action executes when page is loaded, once:

let HandleEvent = (event) => {
 console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent(event)

UPD: Ofcourse it is just example, HandleEvent function will have much more complex logic.

My questions is:

  1. Why?
  2. How to make it work properly?

Upvotes: 3

Views: 184

Answers (6)

engineforce
engineforce

Reputation: 3020

What you did was assigning the result of HandleEvent() to the event, instead you should assign the function to it.

Correct statement:

document.getElementById('myElem').onmousedown = HandleEvent;

Upvotes: 0

Ben Aston
Ben Aston

Reputation: 55729

document.getElementById('myElem').onmousedown = HandleEvent;

To pass additional arguments you could use bind:

document.getElementById('myElem').onmousedown = HandleEvent.bind(null, argument1, argument2);

...or you could use a factory function:

document.getElementById('myElem').onmousedown = createHandler();

function createHandler() {
  var a = calculateA();
  var b = calculateA();
  return function handleEvent() {
     //use a and/or b
  };
}

There are other ways too. Precise code will depend on your use case.

Upvotes: 5

Marc
Marc

Reputation: 317

If you want to pass an attribute

let HandleEvent = (event) => {
 console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent.bind(attribute)

Upvotes: 1

Juanjo Salvador
Juanjo Salvador

Reputation: 1093

You don't need the event.

let HandleEvent = (event) => 'fired!';
document.getElementById('myElem').onmousedown = HandleEvent

Upvotes: 2

Ruan Mendes
Ruan Mendes

Reputation: 92274

document.getElementById('myElem').onmousedown = HandleEvent;

Would do what you want; you should not execute the handler when assigning it. You should just assign the function reference.

Then you can also assign it as the onload handler, or even call it yourself (if you are not relying on the event object)

Upvotes: 6

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

Remove the event

let HandleEvent = (event) => {
 console.log('fired!')
}
document.getElementById('myElem').onmousedown = HandleEvent

Upvotes: 1

Related Questions