When using Typescript with JQuery, I encountered a strange issue where a click event seemed to be added multiple times each time the user opened a dialog. Despite creating a new SettingsDlog object for each dialog instance, the click event did not behave as expected.
I initially thought that the event was being added to the DOM object independently of the Typescript class, but upon inspection in the DOM explorer, this theory proved incorrect.
To work around this issue, I had to explicitly remove the event handler every time it was called, although I am puzzled as to why this step was necessary given the instantiation of a new SettingsDlog object each time.
The code used to show the dialog is as follows:
let myDlog = new SettingsDlog();
myDlog.closedCallback = "settingsDlog_Closed";
myDlog.show();
Within the show() method of the SettingsDlog class, the click events are bound like so:
show() {
$('#closeX').click({ isOK: false }, this.onClose.bind(this))
$('#btnCancel').click({ isOK: false }, this.onClose.bind(this))
$('#btnOK').click({ isOK: true }, this.onClose.bind(this));
}
Subsequently, when any of the UI elements are clicked to close the dialog, the onClose() method of the SettingsDlog is invoked:
onClose(event) {
this.dialogResult = event.data.isOK;
if (!AppHelper.isNullOrEmpty(this._closedCallback))
MainPage[this._closedCallback](this);
}
Lastly, the _closedCallback function within the MainPage object is triggered:
settingsDlog_Closed(sender: SettingsDlog) {
if (!sender.dialogResult)
return;
// Perform some useful action...
}
Upon further investigation by adding breakpoints to the settingsDlog_Closed method, I observed that additional click events were seemingly being added each time the dialog was displayed again.
To address this anomaly, I resorted to adding the following lines of code as a temporary fix within the onClosed method of the SettingsDlog:
$('#closeX').off('click');
$('#btnCancel').off('click');
$('#btnOK').off('click');
If anyone can shed light on this peculiar behavior, your insights would be greatly appreciated.