sending parameters to a callback function that is listening for arguments

function setmclisten(message, sender, sendResponse) {
  console.log(data);
  if(message['type'] === 'startUp')
  {
    console.log(data);
    sendResponse(data)
  }
}
function QuarryToServer(){
  chrome.runtime.onMessage.removeListener(setmclisten);
  $.ajax({
    type: "GET",
    async: true,
    form: 'formatted',
    url: SERVERURL,
    success: function (data) {
      //sends a get 
      console.log("set startup listener");
      debugger;
      chrome.runtime.onMessage.addListener(setmclisten);
    },
    fail: function () { console.error("error quarrying server"); }
  });
}

I am facing an issue where I need the function to have a name so that I can remove the listener later on. However, when I make it a named function, I lose access to the data variable. If I try to pass it like addListen(func(args)), it will just call the function instead of passing it as a variable. Is there a way to pass the variable and still have the function defined in the global scope? To clarify, I have the setmclisten function and I need it to be named while still being able to pass the data argument and receive the onmessage listener arguments like the message itself.

Answer №1

It appears that I have identified the issue at hand. With additional context, we might offer a more effective solution to help you resolve it. However, for now, an approach involving minimal changes is to keep track of the last listener, as demonstrated below (refer to *** comments):

function setmclisten(message, sender, sendResponse, data) { // *** Ensure `data` param
                                                            // is included at the end
  console.log(data);
  if(message['type'] === 'startUp')
  {
    console.log(data);
    sendResponse(data)
  }
}
let lastListener = null; // *** Keep record of the last listener
function QuarryToServer(){
  // *** Discard the previous listener if one exists
  if (lastListener) {
      chrome.runtime.onMessage.removeListener(lastListener);
      lastListener = null;
  }
  $.ajax({
    type: "GET",
    async: true,
    form: 'formatted',
    url: SERVERURL,
    success: function (data) {
      console.log("set startup listener");
      // *** Establish a new listener and attach it
      lastListener = function(message, sender, sendResponse) {
          return setmclisten(message, sender, sendResponse, data);
          // *** Alternatively, if `this` is crucial in the call:
          // return setmclisten.call(this, message, sender, sendResponse, data);
      };
      chrome.runtime.onMessage.addListener(lastListener);
    },
    fail: function () { console.error("error quarrying server"); }
  });
}

Another approach is to consistently maintain a listener instead of constantly adding and removing it, utilizing the most recent data:

let lastData = null; // ***
function setmclisten(message, sender, sendResponse) {
  if (!lastData) {
    return;
  }
  console.log(lastData);
  if(message['type'] === 'startUp')
  {
    console.log(lastData);
    sendResponse(lastData)
  }
}
function QuarryToServer(){
  $.ajax({
    type: "GET",
    async: true,
    form: 'formatted',
    url: SERVERURL,
    success: function (data) {
      lastData = data; // ***
    },
    fail: function () { console.error("error quarrying server"); }
  });
}

In the provided code snippets, it is assumed that you execute

chrome.runtime.onMessage.addListener(setmcllisten);

one time.

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

Vue.js is limited in its ability to efficiently partition code into easily loadable modules

My current issue: I am facing a challenge with splitting my vue.js code into chunks. Despite trying multiple examples from tutorials, I am unable to successfully separate the components and load them only when necessary. Whenever I attempt to divide the c ...

Learn the process of uploading a file using FormData alongside multer in node js. Experience the issue of receiving undefined in req.file and { } in req.body

Is there a way to successfully upload a file using FormData along with multer in Node.js? I seem to be encountering issues as req.file shows undefined and req.body displays {}. Check out the HTML code snippet below: <input type="file" name=&q ...

Refreshin the attached DOM to a directive without a page reload

Within a directive, I have implemented some text and a video tag in the code below: app.directive('ngAzuremediaplayer', function () { return { restrict: 'AE', priority: 10, link: function (scope, elem, attr ...

Vue components failing to reflect code changes and update accordingly

Initially, the component functions properly, but subsequent changes require me to restart the server in order to see any updates. ...

Is there a way for me to personalize the background of the mui-material datagrid header?

I am looking to update the background design of Mui Datagrid from this image to this image However, I am encountering an issue where the background color does not fully cover the header. I have attempted using "cellClassName:" in the columns but it has n ...

The function Object.defineProperties() allows for reassigning a property's value after it has been initially

The issue arises in the initial code snippet provided below, specifically when dealing with the object book. Initially, the value of book.year is set to 2013. Even after updating the value by setting book.year = 2015, retrieving the value using book.year s ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

Reopen a Kendo UI dialog

Currently, I am utilizing Kendo UI, and my goal is to display a modal dialog when a button is clicked. The issue I am facing is that it works perfectly the first time around. However, upon closing the dialog and attempting to reopen it by clicking the butt ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

What steps can be taken to resolve the error message "AttributeError: 'WebElement' object does not have the attribute 'find_element_class_name'?"

try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements_by_tag_name("article") for article in articles: header = article.find_element_c ...

Jquery Ajax POST not functioning as expected

I have implemented a validation function on button click event using jQuery Ajax. This method displays an alert message if the return value is 1, otherwise it returns true and proceeds to the button method. The validation, alert display, and blocking of t ...

The function $.getJSON() seems to be non-responsive

I've been struggling to solve this issue for quite some time now. The users.json file that I am using can be found in the "JSON" folder alongside the other files. The alert("Before") is functioning properly, but I'm facing difficulty with getting ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Perform a Selenium action to click on each individual HTML 'a' tag on

I am attempting to automate clicking on all the "a" tags within a website using Selenium in Python. However, I found that all the "a" tags I want to click have the same structure as shown in the code snippet below. I tried clicking them by their class si ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...