I am encountering a weird issue while trying to register and fire events in jQuery. My sample code stub is this:
events = {"changeMode": ["mode1"], "changeKeymap": ["keymap1"]}
for(var event in events) {
var listeners = events[event];
for (i=0; i<listeners.length; i++)
{
var listn = listeners[i]
console.log("Activate listener", listn, " For event: ", event);
$("#testing").on(event, function(e, d) {
console.log("Event: ", event);
console.log("Listener invoked is: ", listn);
console.log("Event which is passed is: ", e);
console.log("Data is: ", d);
});
}
}
$("#testing").trigger("changeMode", "random data");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testing"></div>
As you can see, while I am trying to invoke the "changeMode", the listener that is actually getting invoked is "changeKeymap". Actually the listener invoked is the last listener that is defined so I am assuming that somehow it is overwriting other listeners. (I actually have much larger code but essentially this is what the bug I am encountering boils down to.) Can anyone suggest what is happening.
Here is JSFiddle: https://jsfiddle.net/7xyyggz8/
EDIT:
The event fired is correct as suggested by Joel. However the listener that invoked in response to that is somehow incorrect.
EDIT 2:
Updated fiddle and code to use vars.. still encountering the same issue