user2251919
user2251919

Reputation: 675

Using a function as a callback or storing it?

I can do this

var element; // some html node

element.addEventListener("click", function() {
     alert(1);
}, false);

Or this;

var clickFunc = function() {
    alert(1);
}

element.addEventListener("click", clickFunc, false);

Does it matter which one I do? I have read all over the internet that the two approaches differ and I am struggling to see why?

Upvotes: 2

Views: 62

Answers (4)

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

I personally prefer second option. It's more reusable and testable also you can use removeEventListener. There isn't any difference in terms of performance and functionality.

Upvotes: 1

Tomas Kirda
Tomas Kirda

Reputation: 8413

Both are doing the same thing. It's just with anonymous function you will not be able to call removeListener.

Upvotes: 1

Dustin Laine
Dustin Laine

Reputation: 38503

Nothing as far as performance or functionality is concerned, but if you are going for any re-usability then the second option is better.

var clickFunc = function() {
    alert(1);
}

element.addEventListener("click", clickFunc, false);
element1.addEventListener("click", clickFunc, false);

Upvotes: 1

Pointy
Pointy

Reputation: 413709

There's a third alternative:

function clickFunc() {
  alert(1);
}

element.addEventListener("click", clickFunc, false);

The advantage here is that the name ("clickFunc") will show up in stack traces if there are exceptions thrown.

You can also do this if you really like typing:

var clickFunc = function clickFunc() {
  alert(1);
};

Or, shorter:

element.addEventListener("click", function clickFunc() {
  alert(1);
}, false);

but those have some minor issues in older browsers.

Upvotes: 2

Related Questions