2
var johnson = button.addEventListener('click', function() {
}); 

In what ways i can use this variable name. can i call the johnson as a function somewhere?

1
  • Missing 3rd argument for addEventListener Commented Apr 19, 2011 at 13:46

3 Answers 3

3

No, because you aren't assigning addEventListener function to the variable, you are assigning the returned value from executing the function (which in this case is actually nothing look here for an example of the return value: http://jsfiddle.net/DKyhW/2/ ).

To assign the function you either need to do:

var johnson = button.addEventListener; 
//this assigns the eventlistener function to the variable.
johnson('click', function () {});

or

var johnson = function () {} //assigns function to variable.

button.addEventListener('click', johnson);
Sign up to request clarification or add additional context in comments.

Comments

3

johnson will contain the return value of addEventListener, but addEventListener doesn't return anything. johnson will be null.

You can certainly used a named function or a variable that points to a function as an event listener, though:

    var johnson = function() {
      //do stuff
    }

button.addEventListener('click', johnson);

Now you can call that listener function by clicking the button, or by calling

johnson();

Comments

2

Since addEventListener does not have a return value, your variable will be bound to undefined being virtually useless.

Maybe you wanted to something like this:

var johnson = function() { ... }

button.addEventListener('click', johnson);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.