将参数传递给在argumnet上侦听的回调函数

问题描述 投票:0回答:1
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))一样传递它它只会调用函数而不是将其作为变量传递,是否可以通过该函数传递变量,同时仍在全局范围内定义函数要澄清:所以这里有setmclisten,我需要它成为一个命名函数,同时传递数据参数并接收像messge本身一样的onmessge侦听器的错误信息]

javascript ajax callback
1个回答
0
投票

我想我看到了问题。有了更多的上下文,我们也许可以更好地帮助您解决问题,但是最小的更改方法是记住最后一个侦听器,如下所示(请参见***注释):

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"); }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.