Strange occurrences with Javascript events, removeEventListener failing to function

I am facing a challenge with removing event listeners in my code to prevent multiple calls to an event. I need the flexibility to call these functions multiple times without causing conflicts.

Currently, my solution is not effectively removing the event listener from the "imageEvilRace" element. This results in the "killRacer" function targeting and deleting the same image on subsequent calls, even though it should only affect the new target. It seems to retain a reference to the first image even when it shouldn't.

Below are the crucial parts of the relevant functions that pertain to my issue:

function killRacer() {
    var listOfRaceImgs = getListOfRaceImages();
    var killRacerTimerID = setInterval(moveEvilRaceImage.bind(null, randomRacer), 40);
    imageEvilRace.addEventListener("stopKiller", stopMovingKillerImage.bind(null, killRacerTimerID, randomRacer));
}

function moveEvilRaceImage(imageToKill) {
    imageEvilRace.dispatchEvent(stopKillerEvent);
}

function stopMovingKillerImage(killRacerTimerID, randomRacer) {
    clearInterval(killRacerTimerID);
    randomRacer.style.display = "none";
    randomRacer.style.left = 0 + "px";
    imageEvilRace.src = explosionImageSource;
    imageEvilRace.removeEventListener("stopKiller", stopMovingKillerImage);
}

Answer №1

The callback you're trying to unbind is stopMovingKillerImage, but the bound callback is actually

stopMovingKillerImage.bind(null, killRacerTimerID, randomRacer)
. They are two separate functions.

To handle a single-use event handler like this, I suggest creating a wrapper function that correctly stores the intended function:

function bindOnce(obj, eventType, func) {
    var newFunc = function() {
        func.apply(this, arguments);
        obj.removeEventListener(eventType, newFunc);
    };

    obj.addEventListener(eventType, newFunc);
}

bindOnce(imageEvilRace, "stopKiller", stopMovingKillerImage.bind(null, killRacerTimerID, randomRacer));

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

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

The use of a nested loop in jQuery to render elements using the appendPe function only displays

Trying to fetch data from a drinks API using an AJAX call and then looping through to display the ingredients on the page. However, only the last item in the loop is being displayed when appending the results with jQuery. I am aware of some null values and ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Exploring the components of the scene with three.js

I have a desire to explore each element within a particular scene. These elements come in various forms such as THREE.Object3D, THREE.Mesh, and more. Some of these elements contain a property called children, which is essentially an array of other elements ...

Adjust the texture rotation on a PlaneGeometry by 45 degrees using UV coordinates

Trying to apply a rotated texture onto a PlaneGeometry has been a bit of a challenge for me. I have a 44x44 diamond-shaped texture that you can view here: https://i.sstatic.net/Babx0.png My goal is to map this diamond texture onto the plane geometry usi ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

Losing a specific characteristic of data occurs when assigning a JavaScript object

After dedicating a full day to investigating this case, I found myself losing hope. const Tests = (state = INIT_STATE, action) => { switch (action.type) { case GET_TEST_DETAIL: return { ...state, test: {}, error ...

The functionality of the Express module in a Node.js environment is not functioning as

I am currently utilizing the 'express' module within Node JS following the example here Upon attempting to run the server and accessing 'localhost:8000', I encounter the following error: Error: No default engine was specified and no e ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

jQuery - growlUI Notification feature utilizing a screen-scraped tweet for real-time

I am attempting to retrieve my most recent tweet and display it in a notification using JavaScript and jQuery's growlUI() function. After successfully pulling my tweet using PHP and storing it in a JavaScript variable called "test," I need to modify ...

Obtain the title of the text generated by clicking the button using a script function

I am working on a piece of code that generates a text box within a button's onclick function. My goal is to retrieve the name value of each text box using PHP. <script language="javascript"> var i = 1; function changeIt() ...

Inspect the table and format the tr content in bold depending on the values found in two corresponding columns within the same table

Looking to create a responsive table where row content becomes bold if it matches the current date. Hiding the first-child th & td as they are only needed for a specific function. Comparing values in <td data-label="TodaysDate">06-05-2020</t ...

JavaScript function to easily determine the precise position of an element across different web browsers

MY APOLOGIES - I made an incorrect assumption due to an error in another script. ** * but hey, it turns out this function is actually quite useful ;) Many thanks for the assistance. !~~ This is the function I have: function findPos(obj) { var c ...

Direct the user to a webpage with the option for postback functionality or caching

I'm encountering an issue on my webforms site with 2 menus. When a button is clicked on a page, it triggers some C# events through a webservice (ajax) and then redirects to another page using history.go(-1). The problem arises when I create a session ...

What is the best way to handle the completion of the mongoose .exec function?

I am a bit confused about asynchronous code in Node.js and Mongoose. In simple terms, I want to post an array of usernames and check if each username is in the database. If it is, I want to add it to the valid array, otherwise, add it to the invalid array. ...

Changing the URL for the onClick event of a button in Laravel through AJAX

I am working on a basic form that includes a "Submit" button and an extra "Add" button in a blade template. When the form is submitted, there is an ajax call to a controller for validation of the provided value. Depending on the response from the controlle ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

Using Vue to download a file by linking to the href and incorporating a Vuetify v-btn

Having recently started learning Vue.js, I am currently encountering difficulty with a seemingly simple task. My goal is to add a Vuetify button to my webpage that allows users to download a file. However, I am struggling with getting the href attribute t ...

Is your JS code moving forward without waiting for the Promise to get resolved?

I am facing an issue with my application where it is not waiting for the promise to return before executing other code that depends on the data. I have tried using then() but the next code is still being executed before the values are returned. In my setu ...