0

Im trying to add an event listener to a object for example:

this.startLoading = function(){
     this.a.addEventListener("complete", this.loadingHandler()); this gives me an error
},

this.loadingHandler = function(){
    console.log("im doing something")
}

ERROR: "Uncaught Error: addListener only takes instances of Function. The listener for event "complete" is "undefined"

However if I put the loadingHandler() function inside the scope it works, for example:

this.startLoading = function(){
     var loadingHandler = function(){...}
     this.a.addEventListener("complete", loadingHandler()); // this works
 },

Im not sure what instances of a function means in that regard?

3
  • If loadingHandler is exactly the same as this.loadingHandler, I thought both wouldn't work... Commented Jun 24, 2014 at 12:46
  • possible duplicate of Select Box Navigation: widow opening on page load rather than change Commented Jun 24, 2014 at 12:48
  • 1
    Yes there are a zillion duplicates of this question. However, the nature of the issue is subtle, and the basic similarities between the questions are often not clear to JavaScript newcomers. Commented Jun 24, 2014 at 12:50

1 Answer 1

1

When you put () after a reference to a function, that means to call the function, and the value of the expression is whatever the function returns.

Your second example, that you say works, actually will not work, and you'll get the same error if the "startLoading" function is called.

Because you probably need to retain the proper context (this), what you probably need is

this.a.addEventListener("complete", this.loadingHandler.bind(this));

The .bind() method returns a function (exactly what addEventListener requires) that in turn will invoke your function such that this has the value requested.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! now i understand what bind does. Wow

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.