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

Ways to determine cleanliness or filthiness in an Angular 5 modal form?

I have a form within a modal and I only want to submit the form if there are any changes made to the form fields. Here is a snippet of my form: HTML <form [formGroup]="productForm" *ngIf="productForm" (ngSubmit)="submitUpdatedRecord(productForm.value) ...

Error: React JS is unable to access the property 'path' because it is undefined

Currently, I am encountering an issue while setting the src of my image in React to this.props.file[0].path. The problem arises because this state has not been set yet, resulting in a TypeError: Cannot read property 'path' of undefined. To provid ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

Create a PDF document and provide a reply

Recently, I encountered an issue while trying to generate a PDF using KnpSnappyBundle on Symfony. Upon running a route through AJAX, the code executes without errors but fails to produce the PDF file. The objective is to create a PDF in a new tab or wind ...

I am in search of a specialized 3D camera with a unique effect

I am seeking assistance with animating a camera to replicate or closely resemble the effect seen in this demo: Any help would be greatly appreciated. ...

Clicking on React Js reverses an array that had previously been unreversed

My issue involves an array pulled from a database that I have reversed so that the newest entry is displayed at the top when a button is clicked, opening a modal-style window. However, when the array is displayed in the modal window, it appears to be flipp ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Is it possible for an onclick attribute to assign a function to document.getElementById without overwriting the existing value?

I want to create a numeric keypad in HTML with numbers 1-9, and I'm unsure if JavaScript can handle an onclick function for each key to show the number in the display div. What would be the most effective way to achieve this? <div id="display"> ...

A different approach to joining strings

Is there a different method to combine a '#' symbol like in the code snippet below? radioButtonID = '#' + radioButtonID; ...

Launching URLs from JSON data in the system browser - Apache Cordova

I am facing an issue with opening links from a JSON in the system browser on both Android and iOS devices. The link generated by the function appears as: {{item.addressLink}}, instead of bit.ly/xyzxyz Here is what I currently have: <a href="#" ng-cl ...

The functionality of findDOMNode is no longer supported

My website, built using React, features a calendar that allows users to select a date and time range with the help of the react-advanced-datetimerange-picker library. However, I encounter some warnings in my index.js file due to the use of <React.Stric ...

Performing height calculations in JavaScript is necessary to recalculate them whenever there is a

A JavaScript function is used to calculate the height of an iframe element and the document height, then determine if the iframe is on or off based on its height and display properties. The issue arises when changing pages— if the height is less than the ...

What exactly does a module's scope entail in browsers and Node.js environments?

Can someone clarify the scope of a module in different environments like browsers and Node? I'm particularly interested in whether a module-level variable is initialized once for the entire application or multiple times. Is each import creating a new ...

Is a missing dependency causing an issue with the React Hook useEffect?

I've encountered an issue with the following code snippet, which seems to only depend on [page]. Despite this, I am receiving the error message: React Hook useEffect has a missing dependency I've come across similar discussions suggesting to com ...

Automatically logging in to a website using an AngularJS form

I am struggling with autologin to a website that has an authentication form built with Angular JS. The form structure looks like this: <form name="loginForm" class="login-form ng-pristine ng-invalid ng-invalid-required"> <div class="tight-fo ...

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

Deactivate Firestore listener in useEffect to cease updates

Looking for a solution with useEffect to stop listening to Firebase Firestore collection changes? Data from Firebase can be retrieved successfully, but encountering issues accessing the unsubscribe function. Any ideas on how to resolve this problem? l ...

Continuously update the content within a paragraph using jQuery

After searching for a jQuery animation that would constantly change text within a paragraph, I stumbled upon a solution at this link : Text changing with animation jquery. However, I encountered a challenge as I wanted to include a bootstrap button beneath ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...