将参数传递给监听参数的回调函数

passing argument to callback function listening on argumnets

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"); }
  });
}

我遇到的问题我需要命名该函数,以便稍后删除侦听器但是当我将其命名为函数时我无法访问数据变量,如果我尝试像 addListen(func( args)) 它只会调用函数而不是将其作为变量传递 有没有一种方法可以传递变量,同时仍然具有在全局范围内定义的函数 clarify:so 那里有 setmclisten,我需要它是一个命名函数,同时传递数据参数并接收 onmessge 侦听器参数,比如 messge it self

我想我明白问题所在了。有了更多的上下文,我们也许能够帮助您以更好的方式解决它,但最小的改变方法是记住最后一个听众,就像这样(参见 *** 评论):

function setmclisten(message, sender, sendResponse, data) { // *** Note `data` param
                                                            // at end
  console.log(data);
  if(message['type'] === 'startUp')
  {
    console.log(data);
    sendResponse(data)
  }
}
let lastListener = null; // *** Remember the last listener
function QuarryToServer(){
  // *** Remove the last listener if any
  if (lastListener) {
      chrome.runtime.onMessage.removeListener(lastListener);
      lastListener = null;
  }
  $.ajax({
    type: "GET",
    async: true,
    form: 'formatted',
    url: SERVERURL,
    success: function (data) {
      //sends a get 
      console.log("set startup listener");
      // *** Create a new listener and attach it
      lastListener = function(message, sender, sendResponse) {
          return setmclisten(message, sender, sendResponse, data);
          // *** Or if `this` is important in the call:
          // return setmclisten.call(this, message, sender, sendResponse, data);
      };
      chrome.runtime.onMessage.addListener(lastListener);
    },
    fail: function () { console.error("error quarrying server"); }
  });
}

或者,总是附加一个侦听器而不是添加和删除它,并让它使用最新数据:

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"); }
  });
}

在上面,我假设你这样做

chrome.runtime.onMessage.addListener(setmclisten);

一次。