I have a function in my controller that targets a button, then attaches an event listener, which should call a function on the click event but it is calling it automatically when the page loads.
How do I change this to only call the function when I click on goBtn?
onAfterRendering: function() {
var goBtn = document.getElementById('__xmlview1--smartFilterId-btnGo');
console.log("goBtn = ", goBtn);
goBtn.addEventListener("click", this._onGoClick(event), false);
},
_onGoClick: function(event) {
console.log("Event attaaaaached!!! = ", event);
// do something else
},
The problem is that you are already evaluating your event handler. This calls the _onGoClick
method immediately (as soon as this line is reached).
goBtn.addEventListener("click", this._onGoClick(event), false);
What you want to do is pass a function to addEventListener
that gets called later.
goBtn.addEventListener("click", this._onGoClick, false);
On a different note your code is meant to break in the near future. The id __xmlview1--smartFilterId-btnGo
is dynamically created and can change as soon as you launch the app in a different context.