Why was the event handler attached and for what purpose does it serve in this particular location?

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.

Answer №1

Big shoutout to @Patrick Evans for steering me in the right direction on this one. I finally found the solution I was looking for. How to determine if a dynamically attached event listener exists or not?

After considering Patrick's advice, I decided to incorporate a static variable into the SettingsDlog class that switches to true once the "show" method is executed. This prevents any future instances of the class from redundantly attaching event handlers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The use of event.returnValue in jQuery has been marked as deprecated

Every time I create a webpage using jQuery version , I encounter a warning message in the Console of Google Chrome. Is there a specific piece of code I can use to avoid this warning? Note that I am currently learning jQuery. The warning reads: event.retu ...

What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online. let users = { Alan: { age: 27, online: false }, Jeff: { age ...

CodeIgniter encountering a dilemma with session logout functionality

if ($this->Adminmodel->check_credentials($this->input->post('email'), $this->input->post('password')) =="true") { redirect("admin/dashboard"); } ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

What is the appropriate directory to place the `typescript` package in order for WebStorm to recognize it?

According to the information on this webpage: The Configure TypeScript Compiler dialog box provides two options: Detect: WebStorm will look for a typescript package within the current project. If it finds one, it will use that package. Otherwise ...

Implementing a secure route in Next.js by utilizing a JWT token obtained from a customized backend system

Currently, I am in the process of developing a full-stack application utilizing NestJS for the backend and Next.js for the frontend. Within my NestJS backend, I have implemented stateless authentication using jwt and passport. My next goal is to establis ...

Error encountered while making a jQuery AJAX request to a .NET Web API

I am currently testing a basic ApiController: namespace Example.Controllers { public class FilesController : ApiController { Files[] files = new Files[] { new Files { ID = 1, Type = 1, Name = "File1"}, ne ...

Passing a jQuery data attribute to another page

Seeking a way to transfer data stored in a data attribute to the next page, below is my approach: Firstly, I assign a class and data attribute to all anchor tags using the following code: jQuery("a").addClass("wptl_link"); jQuery('a').attr(&apo ...

Ways to display closing tag in minimized code in JavaScript documents

I am encountering an issue where the closing tag of folded code is visible in my HTML file, but not in my JS files (specifically JSX syntax). I apologize if this is a trivial question, but I am hopeful that someone can assist me in making the closing tag ...

Managing JSON data files in an Express application

I'm facing a challenge with file upload using express.js. I currently have this mongoose schema: { title: { type: String, required: true, min: 1, max: 1024, }, whatToRead: [{ type: String }], questions: [ { question: { ...

Trouble with a Userscript focused on Styling

Starting off by admitting my limited knowledge in coding, I am determined to finish this simple script. Despite being aware of the script's limitations, I am struggling to understand why it is not functioning as intended. I have attempted to utilize f ...

I am interested in displaying stars in accordance with an array element that is provided as a parameter to my template

I encountered an issue while trying to iterate over an array element with an ID of {{doctor.16}}. I initially attempted to use if conditions as a workaround, but unfortunately, that also proved unsuccessful. Can someone please provide assistance? Here is ...

How can I combine jQuery UI Themeroller with my own custom jQuery UI widget?

I am reaping the advantages of Themeroller in conjunction with the standard widgets provided by jQuery UI. The part that perplexes me is integrating Themeroller with a custom widget built on top of the jQuery UI widget factory. This excerpt from the help ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

Activate a function for a targeted ajax request within a global $.ajax event

I have a series of 3-4 ajax calls that are scheduled to be executed at some point. In one of these calls, I want to activate a function on the global ajaxSend event. This particular ajax call may not be the first or last in the sequence. However, when I at ...

Listen for incoming data from the client in the form of an ArrayBuffer

I have been utilizing the ws library within nodejs to develop a small cursor lobby where players can interact. I have managed to utilize the server to send ArrayBuffers with bit streams to the client and successfully decode them. However, I am encountering ...

After updating from Bootstrap 3 to Bootstrap 5, I encountered an issue where jQuery is no longer functioning properly in Visual

Despite browsing numerous questions on StackOverflow related to this topic, I have not been able to find a solution to my specific issue. I recently set up a new MVC Solution using .NET Framework and decided to upgrade from Bootstrap 3.x to Bootstrap 5.x. ...