Julius Doan Julius Doan - 2 years ago 116
Javascript Question

RemoveEventListener without running function

So I am trying to remove my addEventListener function using the removeEventListener function. I've read alot about it needing to include an handler function, which I have done.

One of the issues is that I am running into is that I would like to remove the eventlistener when I change an input using google's searchbox. Don't mind google but really all what is happening is it is identifying when the input value has changed and providing new results. So a bit of code

var input = document.getElementById('search-input');
var searchBox = new google.maps.places.SearchBox(input);
google.maps.event.addListener(searchBox, 'places_changed', locationChange);

function previousButtonFunction(){
//Does something here and does not return anything. Lets just say it places markers all over the map

function locationChange() {
var previousButton = document.getElementById('previous');
previousButton.removeEventListener('click', previousButtonFunction());
previousButton.addEventListener('click', function () { previousButtonFunction()})

So this code looks like it doesn't make any sense to you probably, but what I am trying to get is that on the first input it would run the add event listener, and not run the removeEventListener function. Once the value of input has changed, I would like to remove the current listener and re-identify the previousButton with a new addeventlistener.

At the first go, I realize that the function of previousButtonFunction() is run, which I thought that it would only run if there was an identified listener. So the first question is the removeEventListener function supposed to run if the eventlistener wasn't added? Second how can I remove the addEventListener without running the function? Would I need to pass in a tracking identifier such as true => run it/false => don't run?

Thanks any help is greatly appreciated

Answer Source

Don't use ()after the function name. You want to pass only a reference to the function. Putting() after the name calls the function and passed the return value. This is a very common mistake.

Change this:

previousButton.removeEventListener('click', previousButtonFunction());

to this:

previousButton.removeEventListener('click', previousButtonFunction);

The same goes for .addEventListener(). Don't put () after the function name unless the function returns another function that you want to be the listener.

FYI, it's a little unclear why you're attempting to remove and then add back the same exactly same listener function. Unless there are multiple listeners on that object and you're trying to change the order of listeners, this is essentially a noop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download