Here is my Javascript module:
const Calculator = (function() {
return {
listen: function (formId) {
this.formId = formId;
this.calculatorForm = document.querySelector(`#form_${this.formId}`);
if (this.calculatorForm) {
this.addEventListeners();
}
},
addEventListeners: function() {
const self = this;
this.calculatorForm.addEventListener('submit', function(event) {
console.log('calculatorForm submit', self);
self.calculatorSubmission(event);
}, false);
},
calculatorSubmission: function(event) {
event.preventDefault();
console.log('Form submitted', this.calculatorForm);
}
};
})();
export default Calculator;
I build all the Javascript using Webpack so I can load modules like this:
import Calculator from './modules/calculator';
The page in question where the Javascript is loaded has tabbed content. Each tab contains a different form, all using the Calculator module so when I switch between tabs, I call:
Calculator.listen('form-id');
The issue I have is when I switch between tabs a few times. Say I view tab 3, 5 times and then fill out and submit form in tab 3. The form is submitted 5 times because of the addEventListener called each time I view tab 3. Make sense?
I'm struggling to fix it - probably because I've been looking at it for hours now and my head is now mash.
Is the problem my module setup?
What best approach to overcoming my issue?
Thanks
I've updated my Calculator to be a class and this seems to work as expected now.
Any improvements welcome!
class Calculator {
constructor() {
if (!Calculator.instance) {
Calculator.instance = this;
}
this.calculatorSubmissionHandler = function(event) {
Calculator.instance.calculatorSubmission(event);
};
return Calculator.instance;
}
listen(formId) {
this.formId = formId;
this.calculatorForm = document.querySelector(`#${this.formId}`);
if (this.calculatorForm) {
this.addEventListeners();
}
}
addEventListeners() {
this.calculatorForm.addEventListener('submit', this.calculatorSubmissionHandler, false);
}
calculatorSubmission(event) {
event.preventDefault();
console.log('Form submitted', Calculator.instance.formId);
}
}