Using JavaScript to Add Event Listeners with Callback Functions and Arguments

I am facing a situation where I have an event handler that needs parameters and triggers a callback function using window.setTimeout. To attach the event handler, I utilize bind.

The callback function receives additional parameters. I have experimented with both callback(parameters) and `callback.call(this,parameters).

Here is an example of the code:

var element=document.querySelector('h1');
element.onclick=function(e) {
    delay(test.bind(element,'from original','also from original',e));
}
function test(a,b,c,d,e) {
    alert(this);    //  element
    alert(a);       //  from original
    alert(b);       //  also from original
    alert(c);       //  event
    alert(d);       //  from delayed
    alert(e);       //  also from delayed
}
function delay(callback) {
    window.setTimeout(delayed,100);
    function delayed() {
        //  callback.call(this,'from delayed','also from delayed');
        callback('from delayed','also from delayed');
    }
}

In my testing, I noticed that the callback receives parameters in the following order:

  1. Parameters from the original function
  2. The event itself
  3. Parameters from the function calling the callback

Additionally, the callback function's this refers to the initial element, regardless of setting it differently when using .call.

Although I can work around this issue, I am curious about its formal explanation. I haven't found any documentation addressing an event listener with a callback.

My questions are:

  1. Where can I find documentation on the parameter ordering?
  2. Why does this remain unchanged despite attempts to modify it?

Thank you

Answer №1

According to the bind() explanation:

The bind() function creates a new function that, when called, has its this keyword specified, along with a sequence of arguments preceding any other provided when the new function is invoked.

Therefore, in this scenario:

test.bind(element,'from original','also from original',e)

a new function will be produced that specifically uses those initial arguments before incorporating any additional ones. This ensures that the function follows the specified order upon execution.


Regarding the usage of this, the issue may arise from executing setTimeout() post binding, leading to unexpected outcomes. Further insights on setTimeout() and this can be found here.

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 anchor events in the DataTable are not responding when clicked, resulting in a failure to load resources

When it comes to jQuery event delegation using on() and live() functions, I have encountered a problem. I am trying to create a function that triggers when a user clicks on an element in a dataTable. Can anyone help me figure out what's going wrong? I ...

Customize the MUI Select component with unique item children

I am currently working on developing a custom Select component that involves mapping through a list of items with specific types. Each item is supposed to display a certain MUI icon based on its type. To achieve this, I have created separate components for ...

Sharing data between ReactJS components using arrays

When I try to send a value from one component to another, the route in my http address shows as undefined instead of the actual value. The server response that I receive is structured like this: https://i.sstatic.net/wxiiM.png The issue arises when I atte ...

How about a unique scrolling experience?

Currently, I am attempting to prevent the scroll position from being locked after a single scroll for one second while scrolling down one section at a time. However, I am encountering unexpected behavior. const [nextSection, setNextSection] = useState(&ap ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

Guide on executing a jar file using JavaScript and obtaining a JSON output

Is there a way to execute and capture the output of a jar file that returns a json using javascript? ...

Using JavaScript and HTML to retrieve information from JSON files in an application

Looking to incorporate i18n into my HTML and JavaScript application, with PHP as the backend. I have a JSON file containing all the keys and translations. Due to limitations on reading JSON files from local storage, I'm unsure of where to store these ...

Using selenium to create a brief pop-up message that appears for a few seconds

I have a Selenium script in Java that opens a Google web page and then closes the browser. Upon closing the browser, I want a pop-up message to appear briefly with the text "Code executed" before fading away after a few seconds. I know that I can achieve t ...

Problem with Shopping Cart: Unable to add items to the "Shopping Cart Page". Error in setting property 'textContent' to null

I am currently immersed in the process of developing a shopping cart using HTML, CSS, and Javascript. I have been following a tutorial on Youtube, but I have encountered a glitch. Despite attempting a few solutions, I continue to encounter the following er ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality: $scope.updateNumbers = function(id, checked, inputs) { if (checked === true) ...

Guide on toggling the expansion and collapse of antd TreeSelect items when a button is clicked

I recently started using the antd library to develop my website. I have successfully implemented the TreeSelect component to display nested options. However, I am currently facing an issue: I am attempting to expand and collapse TreeSelect items when a b ...

Implementing a Masonry layout within an ASP UpdatePanel

I have an ASP-WebPage where I'm using an UpdatePanel with a Dropdown and Output-Div for dynamically generated Cards. These cards are layouted by Masonry. The content of the Output-Div is bound to the Dropdown selection. Initially, the Masonry-Layout ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

The script continues to run despite receiving an XHR error status of 0

I have created an asynchronous audio upload script that is working flawlessly, except for one issue that is really bothering me. The problem lies in the error handling aspect, where an error is being handled with an xhr status of 0 even though the upload p ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...

At what precise moment does the ng-checked function get executed?

When utilizing AngularMaterial, I have implemented ng-checked in the following manner: <md-list> <md-list-item ng-repeat="option in options"> <p> {{ option }} </p> <md-checkbox class="md-secondary" aria-label=" ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...