I found some questions that seem to relate to this, but at the extend of my understanding, mine is different, so here goes. I have greatly simplified my code and even replaced the one line with a comment, but the concept is the same...
function myFunction(options) {
var button;
options.widgets.forEach(function (w) {
button = document.createElement("button");
//add button to the DOM
aListOnMyPage.addEventListener("selectionchanged", function (args) {
var a = button;
});
});
}
So for each of the widgets I am creating a new object and then adding an event listener to a list on the page whose function needs to reference the DOM element (the button) that I created. The behavior I'm seeing is that my button is correctly set at the point where I create the event listener, but when the listener's event fires, button is always a reference to the last button I created. Perhaps it's because it's late, but I can't wrap my head around why it would act like this. Can anyone clarify this for me?