I am currently working on a Table Editor in Javascript and in my code I have the following setup which attempts to add a listener, after the HTML has been generated and appended to the table (a single row):
$(self.tableName + ' tbody').append(htmlString);
$(self.tableName + ' tbody tr').each(function (outerIndex) {
let id = $(this).find('td')[0].innerText;
if (id === elements[0]) {
$(this).find(':input').each(function (inputIndex) {
$(this).change(function (e) {
self.OnFieldValueChanged(objectCollection, elements[0], (inputIndex + 1), $(this).val());
});
if (self.options !== undefined) {
if (self.options.eventListeners !== undefined && self.options.eventListeners[inputIndex] !== undefined) {
let eventListenerArrLength = self.options.eventListeners[inputIndex].length;
for (let eventIndex = 0; eventIndex < eventListenerArrLength; eventIndex++) {
let event = self.options.eventListeners[inputIndex][eventIndex].event;
$(this).on(event, (e) => { self.options.eventListeners[inputIndex][eventIndex].listenerFunction(e) });
}
}
}
});
}
});
Now the weird thing is, this line here
$(this).change(function (e) {
self.OnFieldValueChanged(objectCollection, elements[0], (inputIndex + 1), $(this).val());
});
Actually works as intended. When a value changes in the table, this makes sure that my object representation of the table updates accordingly. However, this piece of the code:
if (self.options !== undefined) {
if (self.options.eventListeners !== undefined && self.options.eventListeners[inputIndex] !== undefined) {
let eventListenerArrLength = self.options.eventListeners[inputIndex].length;
for (let eventIndex = 0; eventIndex < eventListenerArrLength; eventIndex++) {
let event = self.options.eventListeners[inputIndex][eventIndex].event;
$(this).on(event, (e) => { self.options.eventListeners[inputIndex][eventIndex].listenerFunction(e) });
}
}
}
Does not do as intended. While the code does run it doesn't do as I want it to. The idea here is that given an options object, certain columns may have event listeners attached to do who knows what. My current function that I refer to here (self.options.eventListeners[inputIndex][eventIndex].listenerFunction(e)
) is a function designed to only allow certain characters in a field and ignore everything else. So I use the 'keydown' event to achieve this.
But, alas, after the table has made the row and input elements that this code is attached to, the keydown event never triggers the function I added with $(this).on(...)
.
The let event = self.options.eventListeners[inputIndex][eventIndex].event;
is literally just a string taken from an enum like const I've made. It currently holds either "change" or "keydown". So that should be good.
What am I missing about this setup?